title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
questions re: current state of GUI programming with Python
| 707,491
|
<p>I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.</p>
<p>But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.</p>
<p>My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction <em>lower</em> than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.</p>
<p>I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a> ) is honestly somewhat depressing for someone used to Delphi or .NET.</p>
<p>Finally, I've got a couple of questions.</p>
<p>First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.</p>
<p>Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?</p>
<p>It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and <em>open source</em> gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.</p>
| 20
|
2009-04-01T21:53:15Z
| 714,201
|
<p><a href="http://dabodev.com/" rel="nofollow">dabo</a> puts wxPython programming at a higher level like what you're looking for.</p>
| 3
|
2009-04-03T14:38:58Z
|
[
"python",
"user-interface"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 707,683
|
<p>You're very close! <code>string</code> is a module, not a type. You probably want to compare the type of <code>obj</code> against the type object for strings, namely <code>str</code>:</p>
<pre><code>type(obj) == str # this works because str is already a type
</code></pre>
<p>Alternatively:</p>
<pre><code>type(obj) == type('')
</code></pre>
<p>Note, in Python 2, if <code>obj</code> is a unicode type, then neither of the above will work. Nor will <code>isinstance()</code>. See John's comments to this post for how to get around this... I've been trying to remember it for about 10 minutes now, but was having a memory block!</p>
| 3
|
2009-04-01T23:06:36Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 707,685
|
<pre><code>isinstance()
</code></pre>
<p>In your case, <code>isinstance("this is a string", str)</code> will return <code>True</code>.</p>
<p>You may also want to read this: <a href="http://www.canonical.org/~kragen/isinstance/">http://www.canonical.org/~kragen/isinstance/</a></p>
| 106
|
2009-04-01T23:07:02Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 707,687
|
<p>i think this should do it</p>
<pre><code>if isinstance(obj, str)
</code></pre>
| 2
|
2009-04-01T23:07:49Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 707,716
|
<p>For other types, check out the <a href="http://docs.python.org/library/types.html">types</a> module:</p>
<pre><code>>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True
</code></pre>
<p>P.S. Typechecking is a bad idea.</p>
| 20
|
2009-04-01T23:19:36Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 707,732
|
<p><code>isinstance</code> works:</p>
<pre><code>if isinstance(obj, MyClass): do_foo(obj)
</code></pre>
<p><strong>but</strong>, keep in mind: if it looks like a duck, and if it sounds like a duck, it is a duck.</p>
<p>EDIT: For the None type, you can simply do:</p>
<pre><code>if obj is None: obj = MyClass()
</code></pre>
| 30
|
2009-04-01T23:26:47Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 707,812
|
<p>You can always use the <code>type(x) == type(y)</code> trick, where <code>y</code> is something with known type.</p>
<pre><code># check if x is a regular string
type(x) == type('')
# check if x is an integer
type(x) == type(1)
# check if x is a NoneType
type(x) == type(None)
</code></pre>
<p>Often there are better ways of doing that, particularly with any recent python. But if you only want to remember one thing, you can remember that.</p>
<p>In this case, the better ways would be:</p>
<pre><code># check if x is a regular string
type(x) == str
# check if x is either a regular string or a unicode string
type(x) in [str, unicode]
# alternatively:
isinstance(x, basestring)
# check if x is an integer
type(x) == int
# check if x is a NoneType
x is None
</code></pre>
<p>Note the last case: there is only one instance of <code>NoneType</code> in python, and that is <code>None</code>. You'll see NoneType a lot in exceptions (<code>TypeError: 'NoneType' object is unsubscriptable</code> -- happens to me all the time..) but you'll hardly ever need to refer to it in code.</p>
<p>Finally, as fengshaun points out, type checking in python is not always a good idea. It's more pythonic to just use the value as though it is the type you expect, and catch (or allow to propagate) exceptions that result from it.</p>
| 8
|
2009-04-02T00:01:28Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 707,836
|
<p>I use <code>type(x) == type(y)</code></p>
<p>For instance, if I want to check something is an array:</p>
<pre><code>type( x ) == type( [] )
</code></pre>
<p>string check:</p>
<pre><code>type( x ) == type( '' ) or type( x ) == type( u'' )
</code></pre>
<p>If you want to check against None, use is</p>
<pre><code>x is None
</code></pre>
| 2
|
2009-04-02T00:10:13Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 707,878
|
<p>First, avoid all type comparisons. They're very, very rarely necessary. Sometimes, they help to check parameter types in a function -- even that's rare. Wrong type data will raise an exception, and that's all you'll ever need.</p>
<p>All of the basic conversion functions will map as equal to the type function.</p>
<pre><code>type(9) is int
type(2.5) is float
type('x') is str
type(u'x') is unicode
type(2+3j) is complex
</code></pre>
<p>There are a few other cases.</p>
<pre><code>isinstance( 'x', basestring )
isinstance( u'u', basestring )
isinstance( 9, int )
isinstance( 2.5, float )
isinstance( (2+3j), complex )
</code></pre>
<p>None, BTW, never needs any of this kind of type checking. None is the only instance of NoneType. The None object is a Singleton. Just check for None</p>
<pre><code>variable is None
</code></pre>
<p>BTW, do not use the above in general. Use ordinary exceptions and Python's own natural polymorphism.</p>
| 26
|
2009-04-02T00:34:18Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 712,116
|
<p>It is because you have to write</p>
<pre><code>s="hello"
type(s) == type("")
</code></pre>
<p>type accepts an instance and returns its type. In this case you have to compare two instances' types.</p>
<p>If you need to do preemptive checking, it is better if you check for a supported interface than the type. </p>
<p>The type does not really tell you much, apart of the fact that your code want an instance of a specific type, regardless of the fact that you could have another instance of a completely different type which would be perfectly fine because it implements the same interface.</p>
<p>For example, suppose you have this code</p>
<pre><code>def firstElement(parameter):
return parameter[0]
</code></pre>
<p>Now, suppose you say: I want this code to accept only a tuple.</p>
<pre><code>import types
def firstElement(parameter):
if type(parameter) != types.TupleType:
raise TypeError("function accepts only a tuple")
return parameter[0]
</code></pre>
<p>This is reducing the reusability of this routine. It won't work if you pass a list, or a string, or a numpy.array. Something better would be </p>
<pre><code>def firstElement(parameter):
if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
raise TypeError("interface violation")
return parameter[0]
</code></pre>
<p>but there's no point in doing it: parameter[0] will raise an exception if the protocol is not satisfied anyway... this of course unless you want to prevent side effects or having to recover from calls that you could invoke before failing. (Stupid) example, just to make the point:</p>
<pre><code>def firstElement(parameter):
if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
raise TypeError("interface violation")
os.system("rm file")
return parameter[0]
</code></pre>
<p>in this case, your code will raise an exception before running the system() call. Without interface checks, you would have removed the file, and then raised the exception.</p>
| 5
|
2009-04-03T00:14:45Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 10,049,518
|
<p>Type doesn't work on certain classes. If you're not sure of the object's type use the <code>__class__</code> method, as so:</p>
<pre><code>>>>obj = 'a string'
>>>obj.__class__ == str
True
</code></pre>
<p>Also see this article - <a href="http://www.siafoo.net/article/56" rel="nofollow">http://www.siafoo.net/article/56</a></p>
| 1
|
2012-04-06T21:34:25Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 14,640,097
|
<p>To get the type, use the <code>__class__</code> member, as in <code>unknown_thing.__class__</code></p>
<p>Talk of duck-typing is useless here because it doesn't answer a perfectly good question. In my application code I never need to know the type of something, but it's still useful to have a way to learn an object's type. Sometimes I need to get the actual class to validate a unit test. Duck typing gets in the way there because all possible objects have the same API, but only one is correct. Also, sometimes I'm maintaining somebody else's code, and I have no idea what kind of object I've been passed. This is my biggest problem with dynamically typed languages like Python. Version 1 is very easy and quick to develop. Version 2 is a pain in the buns, especially if you didn't write version 1. So sometimes, when I'm working with a function I didn't write, I need to know the type of a parameter, just so I know what methods I can call on it. </p>
<p>That's where the <code>__class__</code> parameter comes in handy. That (as far as I can tell) is the best way (maybe the only way) to get an object's type.</p>
| 0
|
2013-02-01T05:07:22Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 14,787,321
|
<p>Use str instead of string </p>
<pre><code>type ( obj ) == str
</code></pre>
<p>Explanation </p>
<pre><code>>>> a = "Hello"
>>> type(a)==str
True
>>> type(a)
<type 'str'>
>>>
</code></pre>
| 2
|
2013-02-09T10:48:30Z
|
[
"python",
"types",
"compare"
] |
How to compare type of an object in Python?
| 707,674
|
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p>
| 85
|
2009-04-01T23:03:05Z
| 37,044,845
|
<p>You can compare classes for check level.</p>
<pre><code>#!/usr/bin/env python
#coding:utf8
class A(object):
def t(self):
print 'A'
def r(self):
print 'rA',
self.t()
class B(A):
def t(self):
print 'B'
class C(A):
def t(self):
print 'C'
class D(B, C):
def t(self):
print 'D',
super(D, self).t()
class E(C, B):
pass
d = D()
d.t()
d.r()
e = E()
e.t()
e.r()
print isinstance(e, D) # False
print isinstance(e, E) # True
print isinstance(e, C) # True
print isinstance(e, B) # True
print isinstance(e, (A,)) # True
print e.__class__ >= A, #False
print e.__class__ <= C, #False
print e.__class__ < E, #False
print e.__class__ <= E #True
</code></pre>
| 0
|
2016-05-05T07:25:19Z
|
[
"python",
"types",
"compare"
] |
web.py: passing initialization / global variables to handler classes?
| 707,841
|
<p>I'm attempting to use web.py with Tokyo Cabinet / pytc and need to pass the db handle (the connection to tokyo cabinet) to my handler classes so they can talk to tokyo cabinet. </p>
<p>Is there a way to pass the handler to the handler class's <strong>init</strong> function? Or should I be putting the handle in globals() ? What is globals() and how do you use it?</p>
| 1
|
2009-04-02T00:12:58Z
| 709,243
|
<p>The best way would be to add a load hook (described <a href="http://webpy.org/cookbook/sqlalchemy" rel="nofollow">here</a> for sqlalchemy). Define a function that connects to Tokyo Cabinet and adds the resulting db object as an .orm attribute to web.ctx, which is always available inside the controller.</p>
| 2
|
2009-04-02T10:47:49Z
|
[
"python",
"web.py"
] |
Which Python Bayesian text classification modules are similar to dbacl?
| 707,879
|
<p>A quick Google search reveals that there are a good number of Bayesian classifiers implemented as Python modules. If I want wrapped, high-level functionality similar to <a href="http://dbacl.sourceforge.net/" rel="nofollow">dbacl</a>, which of those modules is right for me?</p>
<p>Training</p>
<pre><code>% dbacl -l one sample1.txt
% dbacl -l two sample2.txt
</code></pre>
<p>Classification</p>
<pre><code>% dbacl -c one -c two sample3.txt -v
one
</code></pre>
| 11
|
2009-04-02T00:34:26Z
| 707,901
|
<p>I think you'll find the <a href="http://www.nltk.org">nltk</a> helpful. Specifically, the <a href="http://nltk.googlecode.com/svn/trunk/doc/api/nltk.classify-module.html">classify module</a>.</p>
| 9
|
2009-04-02T00:49:04Z
|
[
"python",
"text",
"classification",
"bayesian"
] |
Which Python Bayesian text classification modules are similar to dbacl?
| 707,879
|
<p>A quick Google search reveals that there are a good number of Bayesian classifiers implemented as Python modules. If I want wrapped, high-level functionality similar to <a href="http://dbacl.sourceforge.net/" rel="nofollow">dbacl</a>, which of those modules is right for me?</p>
<p>Training</p>
<pre><code>% dbacl -l one sample1.txt
% dbacl -l two sample2.txt
</code></pre>
<p>Classification</p>
<pre><code>% dbacl -c one -c two sample3.txt -v
one
</code></pre>
| 11
|
2009-04-02T00:34:26Z
| 708,236
|
<p>If you're trying to detect language
<a href="http://cogscicoder.blogspot.com/2009/03/automatic-language-identification-using.html" rel="nofollow">this</a> works fine even with pretty short texts.</p>
<p>The api is pretty close to yours but
I don't know if it is called a Bayesian classifier. </p>
| 0
|
2009-04-02T03:57:28Z
|
[
"python",
"text",
"classification",
"bayesian"
] |
Which Python Bayesian text classification modules are similar to dbacl?
| 707,879
|
<p>A quick Google search reveals that there are a good number of Bayesian classifiers implemented as Python modules. If I want wrapped, high-level functionality similar to <a href="http://dbacl.sourceforge.net/" rel="nofollow">dbacl</a>, which of those modules is right for me?</p>
<p>Training</p>
<pre><code>% dbacl -l one sample1.txt
% dbacl -l two sample2.txt
</code></pre>
<p>Classification</p>
<pre><code>% dbacl -c one -c two sample3.txt -v
one
</code></pre>
| 11
|
2009-04-02T00:34:26Z
| 1,041,350
|
<p>It maybe this can be useful: <a href="http://www.divmod.org/trac/wiki/DivmodReverend" rel="nofollow">http://www.divmod.org/trac/wiki/DivmodReverend</a></p>
| 2
|
2009-06-24T22:29:57Z
|
[
"python",
"text",
"classification",
"bayesian"
] |
Which Python Bayesian text classification modules are similar to dbacl?
| 707,879
|
<p>A quick Google search reveals that there are a good number of Bayesian classifiers implemented as Python modules. If I want wrapped, high-level functionality similar to <a href="http://dbacl.sourceforge.net/" rel="nofollow">dbacl</a>, which of those modules is right for me?</p>
<p>Training</p>
<pre><code>% dbacl -l one sample1.txt
% dbacl -l two sample2.txt
</code></pre>
<p>Classification</p>
<pre><code>% dbacl -c one -c two sample3.txt -v
one
</code></pre>
| 11
|
2009-04-02T00:34:26Z
| 10,737,824
|
<p>Noticing this question.
I put my implementation of a naive Bayesian classifier on gitHub.</p>
<p><a href="https://github.com/milkmeat/beiyesi" rel="nofollow">Here it is - beiyesi</a></p>
<p>It still needs a lot of improvement. Any help is appreciated.</p>
| 1
|
2012-05-24T12:48:28Z
|
[
"python",
"text",
"classification",
"bayesian"
] |
Which Python Bayesian text classification modules are similar to dbacl?
| 707,879
|
<p>A quick Google search reveals that there are a good number of Bayesian classifiers implemented as Python modules. If I want wrapped, high-level functionality similar to <a href="http://dbacl.sourceforge.net/" rel="nofollow">dbacl</a>, which of those modules is right for me?</p>
<p>Training</p>
<pre><code>% dbacl -l one sample1.txt
% dbacl -l two sample2.txt
</code></pre>
<p>Classification</p>
<pre><code>% dbacl -c one -c two sample3.txt -v
one
</code></pre>
| 11
|
2009-04-02T00:34:26Z
| 15,790,667
|
<p>Try <a href="http://mallet.cs.umass.edu" rel="nofollow">Mallet</a> and <a href="http://alias-i.com/lingpipe/" rel="nofollow">LingPipe</a>. they provide more models for the classifier.</p>
| -1
|
2013-04-03T14:50:11Z
|
[
"python",
"text",
"classification",
"bayesian"
] |
Debugging a running python process
| 707,999
|
<p>Is there a way to see a stacktrace of what various threads are doing inside a python process? </p>
<p>Let's suppose I have a thread which allows me some sort of remote access to the process.</p>
| 14
|
2009-04-02T01:45:03Z
| 708,031
|
<p>About 4 years ago, when I was using twisted, manhole was a great way to do what you're asking.</p>
<p><a href="http://twistedmatrix.com/projects/core/documentation/howto/telnet.html" rel="nofollow">http://twistedmatrix.com/projects/core/documentation/howto/telnet.html</a></p>
<p>Right now most of my projects don't use twisted, so I just WingIDE's remote debugging hooks to introspect a running process.</p>
<p><a href="http://www.wingware.com/doc/debug/remote-debugging" rel="nofollow">http://www.wingware.com/doc/debug/remote-debugging</a></p>
| 2
|
2009-04-02T02:04:49Z
|
[
"python",
"remote-debugging"
] |
Debugging a running python process
| 707,999
|
<p>Is there a way to see a stacktrace of what various threads are doing inside a python process? </p>
<p>Let's suppose I have a thread which allows me some sort of remote access to the process.</p>
| 14
|
2009-04-02T01:45:03Z
| 708,201
|
<p><a href="http://winpdb.org/">Winpdb</a> is a <strong>platform independent</strong> graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.</p>
<p>Features:</p>
<ul>
<li>GPL license. Winpdb is Free Software.</li>
<li>Compatible with CPython 2.3 through 2.6 and Python 3000</li>
<li>Compatible with wxPython 2.6 through 2.8</li>
<li>Platform independent, and tested on Ubuntu Gutsy and Windows XP.</li>
<li>User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.</li>
</ul>
<p><img src="http://winpdb.org/images/screenshot%5Fwinpdb%5Fsmall.jpg" alt="Screenshot" /></p>
| 6
|
2009-04-02T03:44:35Z
|
[
"python",
"remote-debugging"
] |
Python SAX parser says XML file is not well-formed
| 708,531
|
<p>I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema. Could this be causing the trouble? If so, then how do I fix it?</p>
<p>Edit: I think I've found the problem. My character data contains "&lt" and "&gt" characters, presumably from html tags. After being parsed, these are converted to "<" and ">" characters, which seems to bother the SAX parser. Is there any way to prevent this from happening?</p>
| 0
|
2009-04-02T06:35:38Z
| 708,537
|
<p>Does the sax parser not give you details about <em>where</em> it thinks it's not well-formed?</p>
<p>Have you tried loading the file into an XML editor and checking it there? Do other XML parsers accept it?</p>
<p>The schema shouldn't change whether or not the XML is well-formed or not; it may well change whether it's <em>valid</em> or not. See the <a href="http://en.wikipedia.org/wiki/Well-formed%5FXML%5Fdocument" rel="nofollow">wikipedia entry for XML well-formedness</a> for a little bit more, or the <a href="http://www.w3.org/XML/Core/#Publications" rel="nofollow">XML specs</a> for a lot more detail :)</p>
<p>EDIT: To represent "&" in text, you should escape it as <code>&amp;</code></p>
<p>So:</p>
<pre><code>&lt
</code></pre>
<p>should be</p>
<pre><code>&amp;lt
</code></pre>
<p>(assuming you really want ampersand, l, t).</p>
| 1
|
2009-04-02T06:38:48Z
|
[
"python",
"xml",
"sax"
] |
Python SAX parser says XML file is not well-formed
| 708,531
|
<p>I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema. Could this be causing the trouble? If so, then how do I fix it?</p>
<p>Edit: I think I've found the problem. My character data contains "&lt" and "&gt" characters, presumably from html tags. After being parsed, these are converted to "<" and ">" characters, which seems to bother the SAX parser. Is there any way to prevent this from happening?</p>
| 0
|
2009-04-02T06:35:38Z
| 708,546
|
<p>I would suggest putting those tags back in and making sure it still works. Then, if you want to take them out, do it one at a time until it breaks.</p>
<p>However, I question the wisdom of taking them out. If it's your XML file, you should understand it better. If it's a third-party XML file, you really shouldn't be fiddling with it (until you understand it better :-).</p>
| 2
|
2009-04-02T06:42:50Z
|
[
"python",
"xml",
"sax"
] |
Python SAX parser says XML file is not well-formed
| 708,531
|
<p>I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema. Could this be causing the trouble? If so, then how do I fix it?</p>
<p>Edit: I think I've found the problem. My character data contains "&lt" and "&gt" characters, presumably from html tags. After being parsed, these are converted to "<" and ">" characters, which seems to bother the SAX parser. Is there any way to prevent this from happening?</p>
| 0
|
2009-04-02T06:35:38Z
| 711,033
|
<p>I would second recommendation to try to parse it using another XML parser. That should give an indication as to whether it's the document that's wrong, or parser.</p>
<p>Also, the actual error message might be useful. One fairly common problem for example is that the xml declaration (if one is used, it's optional) must be the very first thing -- not even whitespace is allowed before it.</p>
| 0
|
2009-04-02T18:32:53Z
|
[
"python",
"xml",
"sax"
] |
Python SAX parser says XML file is not well-formed
| 708,531
|
<p>I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema. Could this be causing the trouble? If so, then how do I fix it?</p>
<p>Edit: I think I've found the problem. My character data contains "&lt" and "&gt" characters, presumably from html tags. After being parsed, these are converted to "<" and ">" characters, which seems to bother the SAX parser. Is there any way to prevent this from happening?</p>
| 0
|
2009-04-02T06:35:38Z
| 715,813
|
<p>You could load it into Firefox, if you don't have an XML editor. Firefox shows you the error.</p>
| 0
|
2009-04-03T21:31:39Z
|
[
"python",
"xml",
"sax"
] |
Python comments: # vs strings
| 708,649
|
<p>I have a question regarding the "standard" way to put comments inside Python source code:</p>
<pre><code>def func():
"Func doc"
... <code>
'TODO: fix this'
#badFunc()
... <more code>
def func():
"Func doc"
... <code>
#TODO: fix this
#badFunc()
... <more code>
</code></pre>
<p>I prefer to write general comments as strings instead of prefixing #'s.
The official python style guide doesn't mention using strings as comments (If I didn't miss it while reading it)</p>
<p>I like it that way mainly because I think the # character looks ugly with comment blocks. As far as I know these strings don't do anything.</p>
<p>The question is: Are there disadvantages in doing this?</p>
| 19
|
2009-04-02T07:24:59Z
| 708,655
|
<p>I think that only the first string literal in a definition (or class) is "special", i.e. gets stored by the interpreter into the defined object's (or class') <a href="http://www.python.org/dev/peps/pep-0257/" rel="nofollow">docstring</a>.</p>
<p>Any other string literals you place in the code will, at the worst, mean the interpreter will build the string value at run-time, and then just throw it away. This means that doing "comments" by littering the code with string constants might cost, performance-wise.</p>
<p>Of course, I have not benchmarked this, and also don't know the Python interpreter well enough to say for sure.</p>
| 4
|
2009-04-02T07:28:17Z
|
[
"python"
] |
Python comments: # vs strings
| 708,649
|
<p>I have a question regarding the "standard" way to put comments inside Python source code:</p>
<pre><code>def func():
"Func doc"
... <code>
'TODO: fix this'
#badFunc()
... <more code>
def func():
"Func doc"
... <code>
#TODO: fix this
#badFunc()
... <more code>
</code></pre>
<p>I prefer to write general comments as strings instead of prefixing #'s.
The official python style guide doesn't mention using strings as comments (If I didn't miss it while reading it)</p>
<p>I like it that way mainly because I think the # character looks ugly with comment blocks. As far as I know these strings don't do anything.</p>
<p>The question is: Are there disadvantages in doing this?</p>
| 19
|
2009-04-02T07:24:59Z
| 708,668
|
<p>The disadvantage, of course, is that someone else reading it will find that the code strings and comment strings are interleaved, which could be confusing.</p>
| 5
|
2009-04-02T07:32:53Z
|
[
"python"
] |
Python comments: # vs strings
| 708,649
|
<p>I have a question regarding the "standard" way to put comments inside Python source code:</p>
<pre><code>def func():
"Func doc"
... <code>
'TODO: fix this'
#badFunc()
... <more code>
def func():
"Func doc"
... <code>
#TODO: fix this
#badFunc()
... <more code>
</code></pre>
<p>I prefer to write general comments as strings instead of prefixing #'s.
The official python style guide doesn't mention using strings as comments (If I didn't miss it while reading it)</p>
<p>I like it that way mainly because I think the # character looks ugly with comment blocks. As far as I know these strings don't do anything.</p>
<p>The question is: Are there disadvantages in doing this?</p>
| 19
|
2009-04-02T07:24:59Z
| 708,674
|
<p>Don't misuse strings (no-op statements) as comments. Docstrings, e.g. the first string in a module, class or function, are special and definitely recommended.</p>
<p>Note that <strong>docstrings are documentation</strong>, and documentation and comments are two different things!</p>
<ul>
<li>Documentation is important to understand <em>what</em> the code does.</li>
<li>Comments explain <em>how</em> the code does it.</li>
</ul>
<p>Documentation is read by people who <em>use</em> your code, comments by people who want to <em>understand</em> your code, e.g. in order to maintain it.</p>
<p>Using strings for commentation has the following (potential) disadvantages:</p>
<ul>
<li>It confuses people who don't know that the string does nothing.</li>
<li>Comments and string literals are highlighted differently in code editors, so your style may make your code harder to read.</li>
<li>It might effect performance and/or memory usage (if the strings are not removed during bytecode compilation, removing comments is done on the scanner level so its definitively cheaper)</li>
</ul>
<p>Most important for Python programmers: It is not pythonic:</p>
<blockquote>
<p>There should be one-- and preferably only one --obvious way to do it.</p>
</blockquote>
<p>Stick to the standards, use comments.</p>
| 53
|
2009-04-02T07:36:08Z
|
[
"python"
] |
SQLAlchemy - INSERT OR REPLACE equivalent
| 708,762
|
<p>does anybody know what is the equivalent to SQL "INSERT OR REPLACE" clause in SQLAlchemy and its SQL expression language?</p>
<p>Many thanks -- honzas</p>
| 9
|
2009-04-02T08:05:37Z
| 708,769
|
<pre><code>Session.save_or_update(model)
</code></pre>
| 6
|
2009-04-02T08:11:02Z
|
[
"python",
"sqlalchemy"
] |
SQLAlchemy - INSERT OR REPLACE equivalent
| 708,762
|
<p>does anybody know what is the equivalent to SQL "INSERT OR REPLACE" clause in SQLAlchemy and its SQL expression language?</p>
<p>Many thanks -- honzas</p>
| 9
|
2009-04-02T08:05:37Z
| 709,452
|
<p>I don't think (correct me if I'm wrong) INSERT OR REPLACE is in any of the SQL standards; it's an SQLite-specific thing. There is MERGE, but that isn't supported by all dialects either. So it's not available in SQLAlchemy's general dialect.</p>
<p>The cleanest solution is to use Session, as suggested by M. Utku. You could also use SAVEPOINTs to save, try: an insert, except IntegrityError: then rollback and do an update instead. A third solution is to write your INSERT with an OUTER JOIN and a WHERE clause that filters on the rows with nulls.</p>
| 3
|
2009-04-02T12:10:45Z
|
[
"python",
"sqlalchemy"
] |
SQLAlchemy - INSERT OR REPLACE equivalent
| 708,762
|
<p>does anybody know what is the equivalent to SQL "INSERT OR REPLACE" clause in SQLAlchemy and its SQL expression language?</p>
<p>Many thanks -- honzas</p>
| 9
|
2009-04-02T08:05:37Z
| 2,602,292
|
<p>What about <code>Session.merge</code>?</p>
<pre><code>Session.merge(instance, load=True, **kw)
</code></pre>
<p>Copy the state an instance onto the persistent instance with the same identifier.</p>
<p>If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with cascade="merge".</p>
<p>from <a href="http://www.sqlalchemy.org/docs/reference/orm/sessions.html">http://www.sqlalchemy.org/docs/reference/orm/sessions.html</a></p>
| 5
|
2010-04-08T17:58:19Z
|
[
"python",
"sqlalchemy"
] |
SQLAlchemy - INSERT OR REPLACE equivalent
| 708,762
|
<p>does anybody know what is the equivalent to SQL "INSERT OR REPLACE" clause in SQLAlchemy and its SQL expression language?</p>
<p>Many thanks -- honzas</p>
| 9
|
2009-04-02T08:05:37Z
| 5,745,573
|
<p>You can use <code>OR REPLACE</code> as a so-called <code>prefix</code> in your SQLAlchemy <code>Insert</code> -- the documentation for how to place <code>OR REPLACE</code> between <code>INSERT</code> and <code>INTO</code> in your SQL statement is <a href="http://www.sqlalchemy.org/docs/core/expression_api.html?highlight=prefix#sqlalchemy.sql.expression.Insert.prefix_with" rel="nofollow">here</a></p>
| 1
|
2011-04-21T14:35:43Z
|
[
"python",
"sqlalchemy"
] |
How Much Traffic Can Shared Web Hosting (for a Python Django site) support?
| 708,799
|
<p>Someone in this thread</p>
<p><a href="http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take">http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take</a></p>
<p>stated that a $5/mo shared hosting account on Reliablesite.net can support 10,000 - 20,000 unique users/day and 100,000 - 200,000 pageviews/day.
That seems awfully high for a $5/mo account. And someone else told me it's far less than that. What's your experience?</p>
<p>I have a site based on Python, Django, MySQL/Postgresql. It doesn't have any video or other bandwidth heavy elements, but the whole site is dynamic, each page takes about 5 to 10 DB query, 90% reads, 10% writes.</p>
<p>Reliablesite.net is an ASP.NET hosting company. Any Python/LAMP hosting firm that can support 100-200,000 pageviews on a shared hosting account? If not, what kind of numbers am I looking at? Any suggestions for good hosting firms?</p>
<p>Thanks</p>
| 4
|
2009-04-02T08:27:42Z
| 708,805
|
<p>If your application is optimized, you shared hosting account can handle 10k unique visitors per day.</p>
<p>You can find a great hosting for your needs at WFT (<a href="http://www.webhostingtalk.com" rel="nofollow">WebHostingTalk</a>)</p>
<p>One of the biggest hosting provider is GoDaddy (I RECOMMEND IT). Their shared hosting plan with Python starts from $7/month. With them you can host multiple websites on the same account without extra charge.</p>
<p><a href="http://www.godaddy.com/gdshop/hosting/shared.asp?ci=9009" rel="nofollow">http://www.godaddy.com/gdshop/hosting/shared.asp?ci=9009</a></p>
<p>And also take a look at this offer: <a href="http://mediatemple.net/webhosting/gs/features/" rel="nofollow">http://mediatemple.net/webhosting/gs/features/</a></p>
<p>(mt) MediaTemplate company is not that big as GoDaddy but is also in good standing. Reliable.net is too small.</p>
<p>So, here recommended options are:</p>
<ul>
<li><a href="http://www.godaddy.com" rel="nofollow">GoDaddy</a> - <a href="http://www.bizshark.com/company/godaddy.com" rel="nofollow">Info</a> - <a href="http://alexa.com/siteinfo/godaddy.com" rel="nofollow">Alexa Rank: ~410</a></li>
<li><a href="http://www.hostgator.com" rel="nofollow">HostGator</a> - <a href="http://www.bizshark.com/company/hostgator.com" rel="nofollow">Info</a> - <a href="http://alexa.com/siteinfo/hostgator.com" rel="nofollow">Alexa Rank: ~670</a></li>
</ul>
| 0
|
2009-04-02T08:29:29Z
|
[
"python",
"hosting",
"web-hosting",
"shared-hosting"
] |
How Much Traffic Can Shared Web Hosting (for a Python Django site) support?
| 708,799
|
<p>Someone in this thread</p>
<p><a href="http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take">http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take</a></p>
<p>stated that a $5/mo shared hosting account on Reliablesite.net can support 10,000 - 20,000 unique users/day and 100,000 - 200,000 pageviews/day.
That seems awfully high for a $5/mo account. And someone else told me it's far less than that. What's your experience?</p>
<p>I have a site based on Python, Django, MySQL/Postgresql. It doesn't have any video or other bandwidth heavy elements, but the whole site is dynamic, each page takes about 5 to 10 DB query, 90% reads, 10% writes.</p>
<p>Reliablesite.net is an ASP.NET hosting company. Any Python/LAMP hosting firm that can support 100-200,000 pageviews on a shared hosting account? If not, what kind of numbers am I looking at? Any suggestions for good hosting firms?</p>
<p>Thanks</p>
| 4
|
2009-04-02T08:27:42Z
| 708,848
|
<p>100,000 - 200,000 pageviews/day is on average 2 pageviews/s, at most you'll get 10-20 pageviews/s during busy hours. That's not a lot to handle, especially if you have caching.</p>
<p>Anyways, I'd go for VPS. The problem with shared server is that you can never know the pattern of use the other ppl have.</p>
| 3
|
2009-04-02T08:47:46Z
|
[
"python",
"hosting",
"web-hosting",
"shared-hosting"
] |
How Much Traffic Can Shared Web Hosting (for a Python Django site) support?
| 708,799
|
<p>Someone in this thread</p>
<p><a href="http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take">http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take</a></p>
<p>stated that a $5/mo shared hosting account on Reliablesite.net can support 10,000 - 20,000 unique users/day and 100,000 - 200,000 pageviews/day.
That seems awfully high for a $5/mo account. And someone else told me it's far less than that. What's your experience?</p>
<p>I have a site based on Python, Django, MySQL/Postgresql. It doesn't have any video or other bandwidth heavy elements, but the whole site is dynamic, each page takes about 5 to 10 DB query, 90% reads, 10% writes.</p>
<p>Reliablesite.net is an ASP.NET hosting company. Any Python/LAMP hosting firm that can support 100-200,000 pageviews on a shared hosting account? If not, what kind of numbers am I looking at? Any suggestions for good hosting firms?</p>
<p>Thanks</p>
| 4
|
2009-04-02T08:27:42Z
| 709,020
|
<p>Webfaction hosting hosts nearly 10 sites of ours handling over 10k users each day, easily. I am also told that Slicehost is just as good.</p>
<p>Webfaction and Slicehost are often looked upto for mod_wsgi python hosting, which is fast becoming the preferred way to host django apps.</p>
<p>These hosts seem to be on a slightly higher side of the charges/month; but its worth it, as they are reliable.</p>
| 2
|
2009-04-02T09:41:07Z
|
[
"python",
"hosting",
"web-hosting",
"shared-hosting"
] |
How Much Traffic Can Shared Web Hosting (for a Python Django site) support?
| 708,799
|
<p>Someone in this thread</p>
<p><a href="http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take">http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take</a></p>
<p>stated that a $5/mo shared hosting account on Reliablesite.net can support 10,000 - 20,000 unique users/day and 100,000 - 200,000 pageviews/day.
That seems awfully high for a $5/mo account. And someone else told me it's far less than that. What's your experience?</p>
<p>I have a site based on Python, Django, MySQL/Postgresql. It doesn't have any video or other bandwidth heavy elements, but the whole site is dynamic, each page takes about 5 to 10 DB query, 90% reads, 10% writes.</p>
<p>Reliablesite.net is an ASP.NET hosting company. Any Python/LAMP hosting firm that can support 100-200,000 pageviews on a shared hosting account? If not, what kind of numbers am I looking at? Any suggestions for good hosting firms?</p>
<p>Thanks</p>
| 4
|
2009-04-02T08:27:42Z
| 779,328
|
<p>I have been using mysql on shared hosting for a while mainly on informational websites that have gotten at most 300 visits per day. What I have found is that the hosting was barely sufficient to support more than 3 or 4 people on the website at one time without it almost crashing.</p>
<p>Theoretically i think shared hosting with most services could support about about 60 users per hour max efficiently if your users all came one or two at a time. This would equal out to about about 1500 users in one day. This is highly unlikely however because alot of users tend to be online at certain times of the day and you also have to throw in the fact that shared servers get sloppy alot due to abuse from others on the server.</p>
<p>I have heard from reliable sources that some vps hosting thats 40-50 dollars per month have supported 500,000 hits per month. I'm not sure what the websites configurations were though, i doubt the sites ran many dynamic db queries or possibly were simply static.</p>
<p>One other thing that is common on shared hosting is breaking up the file managers with the database hosting. Sometimes your files will do well appearing online but the database that runs your actual website will be lagging extremely due to abuse from your neighbors.</p>
| 1
|
2009-04-22T21:33:21Z
|
[
"python",
"hosting",
"web-hosting",
"shared-hosting"
] |
How Much Traffic Can Shared Web Hosting (for a Python Django site) support?
| 708,799
|
<p>Someone in this thread</p>
<p><a href="http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take">http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take</a></p>
<p>stated that a $5/mo shared hosting account on Reliablesite.net can support 10,000 - 20,000 unique users/day and 100,000 - 200,000 pageviews/day.
That seems awfully high for a $5/mo account. And someone else told me it's far less than that. What's your experience?</p>
<p>I have a site based on Python, Django, MySQL/Postgresql. It doesn't have any video or other bandwidth heavy elements, but the whole site is dynamic, each page takes about 5 to 10 DB query, 90% reads, 10% writes.</p>
<p>Reliablesite.net is an ASP.NET hosting company. Any Python/LAMP hosting firm that can support 100-200,000 pageviews on a shared hosting account? If not, what kind of numbers am I looking at? Any suggestions for good hosting firms?</p>
<p>Thanks</p>
| 4
|
2009-04-02T08:27:42Z
| 840,005
|
<p>I'm with GoDaddy.com and it's true that you can have an unlimited number of sites on the same hosting plan but you are limited to 100 unique users.
This means that it doesn't matter if you have 1 website or 1000 websites on your hosting plan, you can only have 100 visitors at the same time throughout all of your sites combined.
Some visitors could leave and some new ones can arrive but never more than 100 at a time on your GoDaddy hosting plan. I have 10 sites myself so if I have 100 visitors to <a href="http://www.milliondollarmysterychallenge.com" rel="nofollow">http://www.milliondollarmysterychallenge.com</a> then none of my other sites can get any traffic until someone leaves! this stinks! if anybody knows of a better place to host please post a link in the comments.</p>
| 1
|
2009-05-08T14:20:09Z
|
[
"python",
"hosting",
"web-hosting",
"shared-hosting"
] |
How Much Traffic Can Shared Web Hosting (for a Python Django site) support?
| 708,799
|
<p>Someone in this thread</p>
<p><a href="http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take">http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take</a></p>
<p>stated that a $5/mo shared hosting account on Reliablesite.net can support 10,000 - 20,000 unique users/day and 100,000 - 200,000 pageviews/day.
That seems awfully high for a $5/mo account. And someone else told me it's far less than that. What's your experience?</p>
<p>I have a site based on Python, Django, MySQL/Postgresql. It doesn't have any video or other bandwidth heavy elements, but the whole site is dynamic, each page takes about 5 to 10 DB query, 90% reads, 10% writes.</p>
<p>Reliablesite.net is an ASP.NET hosting company. Any Python/LAMP hosting firm that can support 100-200,000 pageviews on a shared hosting account? If not, what kind of numbers am I looking at? Any suggestions for good hosting firms?</p>
<p>Thanks</p>
| 4
|
2009-04-02T08:27:42Z
| 974,025
|
<p>I am hosting with Godaddy. But I am not aware of this 100 users at the same time thing.</p>
| 0
|
2009-06-10T06:42:51Z
|
[
"python",
"hosting",
"web-hosting",
"shared-hosting"
] |
How Much Traffic Can Shared Web Hosting (for a Python Django site) support?
| 708,799
|
<p>Someone in this thread</p>
<p><a href="http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take">http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take</a></p>
<p>stated that a $5/mo shared hosting account on Reliablesite.net can support 10,000 - 20,000 unique users/day and 100,000 - 200,000 pageviews/day.
That seems awfully high for a $5/mo account. And someone else told me it's far less than that. What's your experience?</p>
<p>I have a site based on Python, Django, MySQL/Postgresql. It doesn't have any video or other bandwidth heavy elements, but the whole site is dynamic, each page takes about 5 to 10 DB query, 90% reads, 10% writes.</p>
<p>Reliablesite.net is an ASP.NET hosting company. Any Python/LAMP hosting firm that can support 100-200,000 pageviews on a shared hosting account? If not, what kind of numbers am I looking at? Any suggestions for good hosting firms?</p>
<p>Thanks</p>
| 4
|
2009-04-02T08:27:42Z
| 979,305
|
<p>Most hosts support multiple sites without extra charge. Don't pick GoDaddy because of that. I never used GoDaddy hosting, but use them for domain registration, and they are absolutely terrible. Terrible UI, terrible performance. I would never trust them to host a website. The only reason I use them for domain registration is that they seem to be the cheapest option.</p>
<p>For shared web hosting, especially Python/Django, I recommend WEBFACTION.</p>
| 2
|
2009-06-11T04:17:48Z
|
[
"python",
"hosting",
"web-hosting",
"shared-hosting"
] |
How Much Traffic Can Shared Web Hosting (for a Python Django site) support?
| 708,799
|
<p>Someone in this thread</p>
<p><a href="http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take">http://stackoverflow.com/questions/685162/how-much-traffic-can-shared-web-hosting-take</a></p>
<p>stated that a $5/mo shared hosting account on Reliablesite.net can support 10,000 - 20,000 unique users/day and 100,000 - 200,000 pageviews/day.
That seems awfully high for a $5/mo account. And someone else told me it's far less than that. What's your experience?</p>
<p>I have a site based on Python, Django, MySQL/Postgresql. It doesn't have any video or other bandwidth heavy elements, but the whole site is dynamic, each page takes about 5 to 10 DB query, 90% reads, 10% writes.</p>
<p>Reliablesite.net is an ASP.NET hosting company. Any Python/LAMP hosting firm that can support 100-200,000 pageviews on a shared hosting account? If not, what kind of numbers am I looking at? Any suggestions for good hosting firms?</p>
<p>Thanks</p>
| 4
|
2009-04-02T08:27:42Z
| 994,295
|
<p>That sounds like a stretch for a $5/month shared hosting service. I'd suggest looking in to MediaTemple Grid-Service which is a bit more expensive at $20/month but is more likely to be able to handle your volume and grow with you.</p>
| 0
|
2009-06-15T02:17:14Z
|
[
"python",
"hosting",
"web-hosting",
"shared-hosting"
] |
Why do languages like Java use hierarchical package names, while Python does not?
| 709,036
|
<p>I haven't done enterprise work in Java, but I often see the <a href="http://stackoverflow.com/questions/420945/java-package-name-convention-failure">reverse-domain-name package naming convention</a>. For example, for a Stack Overflow Java package you'd put your code underneath package <code>com.stackoverflow</code>.</p>
<p>I just ran across a Python package that uses the Java-like convention, and I wasn't sure what the arguments for and against it are, or whether they apply to Python in the same way as Java. What are the reasons you'd prefer one over the other? <strong>Do those reasons apply across the languages?</strong></p>
| 13
|
2009-04-02T09:45:13Z
| 709,040
|
<p>The idea is to keep name spaces conflict free. Instead of unreadable UUIDs or the like, the reverse domain name is unlikely to get in someone else's way.
Very simple, but pragmatic.
Moreover when using 3rd party libs it might give you a clue as to where they came from (for updates, support etc.)</p>
| 5
|
2009-04-02T09:47:13Z
|
[
"java",
"python",
"packages"
] |
Why do languages like Java use hierarchical package names, while Python does not?
| 709,036
|
<p>I haven't done enterprise work in Java, but I often see the <a href="http://stackoverflow.com/questions/420945/java-package-name-convention-failure">reverse-domain-name package naming convention</a>. For example, for a Stack Overflow Java package you'd put your code underneath package <code>com.stackoverflow</code>.</p>
<p>I just ran across a Python package that uses the Java-like convention, and I wasn't sure what the arguments for and against it are, or whether they apply to Python in the same way as Java. What are the reasons you'd prefer one over the other? <strong>Do those reasons apply across the languages?</strong></p>
| 13
|
2009-04-02T09:45:13Z
| 709,100
|
<p>It's a great way of preventing name collisions, and takes full advantage of the existing domain name system, so it requires no additional bureaucracy or registration. It is simple and brilliant.</p>
<p>By reversing the domain name it also gives it a hierarchical structure, which is handy. So you can have sub-packages on the end.</p>
<p>The only downside is the length of the name, but to me that is not a downside at all. I think it is a pretty good idea for any language that would support it.</p>
<p>Why don't JavaScript libraries do it, for example? Their global namespace is a big problem, yet Javascript libraries use simple global identifiers like '$' which clash with other Javascript libraries.</p>
| 10
|
2009-04-02T10:02:10Z
|
[
"java",
"python",
"packages"
] |
Why do languages like Java use hierarchical package names, while Python does not?
| 709,036
|
<p>I haven't done enterprise work in Java, but I often see the <a href="http://stackoverflow.com/questions/420945/java-package-name-convention-failure">reverse-domain-name package naming convention</a>. For example, for a Stack Overflow Java package you'd put your code underneath package <code>com.stackoverflow</code>.</p>
<p>I just ran across a Python package that uses the Java-like convention, and I wasn't sure what the arguments for and against it are, or whether they apply to Python in the same way as Java. What are the reasons you'd prefer one over the other? <strong>Do those reasons apply across the languages?</strong></p>
| 13
|
2009-04-02T09:45:13Z
| 709,105
|
<p>Java is able to do it like this, since it is a recommended Java standard practice, and pretty much universally accepted by the Java community. Python dos not have this convention.</p>
| 0
|
2009-04-02T10:04:05Z
|
[
"java",
"python",
"packages"
] |
Why do languages like Java use hierarchical package names, while Python does not?
| 709,036
|
<p>I haven't done enterprise work in Java, but I often see the <a href="http://stackoverflow.com/questions/420945/java-package-name-convention-failure">reverse-domain-name package naming convention</a>. For example, for a Stack Overflow Java package you'd put your code underneath package <code>com.stackoverflow</code>.</p>
<p>I just ran across a Python package that uses the Java-like convention, and I wasn't sure what the arguments for and against it are, or whether they apply to Python in the same way as Java. What are the reasons you'd prefer one over the other? <strong>Do those reasons apply across the languages?</strong></p>
| 13
|
2009-04-02T09:45:13Z
| 709,150
|
<p>"What are the reasons you'd prefer one over the other?"</p>
<p>Python's style is simpler. Java's style allows same-name products from different organizations.</p>
<p>"Do those reasons apply across the languages?"</p>
<p>Yes. You can easily have top level Python packages named "com", "org", "mil", "net", "edu" and "gov" and put your packages as subpackages in these. </p>
<p><strong>Edit</strong>. You have some complexity when you do this, because <em>everyone</em> has to cooperate and not pollute these top-level packages with their own cruft. </p>
<p>Python didn't start doing that because the namespace collision -- as a practical matter -- turn out to be rather rare.</p>
<p>Java started out doing that because the folks who developed Java foresaw lots of people cluelessly choosing the same name for their packages and needing to sort out the collisions and ownership issues.</p>
<p>Java folks didn't foresee the Open Source community picking weird off-the-wall unique names to avoid name collisions. Everyone who writes an xml parser, interestingly, doesn't call it "parser". They seem to call it "Saxon" or "Xalan" or something completely strange. </p>
| 12
|
2009-04-02T10:18:03Z
|
[
"java",
"python",
"packages"
] |
Why do languages like Java use hierarchical package names, while Python does not?
| 709,036
|
<p>I haven't done enterprise work in Java, but I often see the <a href="http://stackoverflow.com/questions/420945/java-package-name-convention-failure">reverse-domain-name package naming convention</a>. For example, for a Stack Overflow Java package you'd put your code underneath package <code>com.stackoverflow</code>.</p>
<p>I just ran across a Python package that uses the Java-like convention, and I wasn't sure what the arguments for and against it are, or whether they apply to Python in the same way as Java. What are the reasons you'd prefer one over the other? <strong>Do those reasons apply across the languages?</strong></p>
| 13
|
2009-04-02T09:45:13Z
| 709,160
|
<p>Python <em>does</em> have it, it's just a much flatter hierarchy. Look at <code>os.path</code>, for example. And there's nothing stopping library designers making much deeper ones, e.g. Django.</p>
<p>Fundamentally, I think Python is designed on the idea that you want to get stuff done without having to specify or type too much in advance. This greatly helps with scripting and command-line use. There are several parts of 'The Zen of Python' that address the rationale for this:</p>
<ul>
<li>Simple is better than complex.</li>
<li>Flat is better than nested.</li>
<li>Beautiful is better than ugly. (The Java system looks ugly to me.)</li>
</ul>
<p>On the other hand, there's:</p>
<ul>
<li>Namespaces are one honking great idea -- let's do more of those!</li>
</ul>
| 2
|
2009-04-02T10:23:29Z
|
[
"java",
"python",
"packages"
] |
Why do languages like Java use hierarchical package names, while Python does not?
| 709,036
|
<p>I haven't done enterprise work in Java, but I often see the <a href="http://stackoverflow.com/questions/420945/java-package-name-convention-failure">reverse-domain-name package naming convention</a>. For example, for a Stack Overflow Java package you'd put your code underneath package <code>com.stackoverflow</code>.</p>
<p>I just ran across a Python package that uses the Java-like convention, and I wasn't sure what the arguments for and against it are, or whether they apply to Python in the same way as Java. What are the reasons you'd prefer one over the other? <strong>Do those reasons apply across the languages?</strong></p>
| 13
|
2009-04-02T09:45:13Z
| 709,188
|
<p>Python doesn't do this because you end up with a problem -- who owns the "com" package that almost everything else is a subpackage of? Python's method of establishing package heirarchy (through the filesystem heirarchy) does not play well with this convention at all. Java can get away with it because package heirarchy is defined by the structure of the string literals fed to the 'package' statement, so there doesn't need to be an explicit "com" package anywhere.</p>
<p>There's also the question of what to do if you want to publicly release a package but don't own a domain name that's suitable for bodging into the package name, or if you end up changing (or losing) your domain name for some reason. (Do later updates need a different package name? How do you know that com.nifty_consultants.nifty_utility is a newer version of com.joe_blow_software.nifty_utility? Or, conversely, how do you know that it's <em>not</em> a newer version? If you miss your domain renewal and the name gets snatched by a domain camper, and someone else buys the name from them, and they want to publicly release software packages, should they then use the same name that you had already used?)</p>
<p>Domain names and software package names, it seems to me, address two entirely different problems, and have entirely different complicating factors. I personally dislike Java's convention because (IMHO) it violates separation of concerns. Avoiding namespace collisions is nice and all, but I hate the thought of my software's namespace being defined by (and dependent on) the marketing department's interaction with some third-party bureaucracy. </p>
<p>To clarify my point further, in response to JeeBee's comment: In Python, a package is a directory containing an <code>__init__.py</code> file (and presumably one or more module files). A package hierarchy requires that each higher-level package be a full, legitimate package. If two packages (especially from different vendors, but even not-directly-related packages from the same vendor) share a top-level package name, whether that name is 'com' or 'web' or 'utils' or whatever, each one <em>must</em> provide an <code>__init__.py</code> for that top-level package. We must also assume that these packages are likely to be installed in the same place in the directory tree, i.e. site-packages/[pkg]/[subpkg]. The filesystem thus enforces that there is only <em>one</em> <code>[pkg]/__init__.py</code> -- so which one wins? There is not (and cannot be) a general-case correct answer to that question. Nor can we reasonably merge the two files together. Since we can't know what another package might need to do in that <code>__init__.py</code>, subpackages sharing a top-level package cannot be assumed to work when both are installed unless they are specifically written to be compatible with each other (at least in this one file). This would be a distribution nightmare and would pretty much invalidate the entire point of nesting packages. This is not specific to reverse-domain-name package hierarchies, though they provide the most obvious bad example and (IMO) are philosophically questionable -- it's really the practical issue of shared top-level packages, rather than the philosophical questions, that are my main concern here. </p>
<p>(On the other hand, a single large package using subpackages to better organize itself is a great idea, since those subpackages <em>are</em> specifically designed to work and live together. This is not so common in Python, though, because a single conceptual package doesn't tend to require a large enough number of files to need the extra layer of organization.)</p>
| 18
|
2009-04-02T10:32:12Z
|
[
"java",
"python",
"packages"
] |
Why do languages like Java use hierarchical package names, while Python does not?
| 709,036
|
<p>I haven't done enterprise work in Java, but I often see the <a href="http://stackoverflow.com/questions/420945/java-package-name-convention-failure">reverse-domain-name package naming convention</a>. For example, for a Stack Overflow Java package you'd put your code underneath package <code>com.stackoverflow</code>.</p>
<p>I just ran across a Python package that uses the Java-like convention, and I wasn't sure what the arguments for and against it are, or whether they apply to Python in the same way as Java. What are the reasons you'd prefer one over the other? <strong>Do those reasons apply across the languages?</strong></p>
| 13
|
2009-04-02T09:45:13Z
| 711,380
|
<p>If Guido himself announced that the reverse domain convention ought to be followed, it wouldn't be adopted, unless there were significant changes to the implementation of <code>import</code> in python.</p>
<p>Consider: python searches an import path at run-time with a fail-fast algorithm; java searches a path with an exhaustive algorithm both at compile-time and run-time. Go ahead, try arranging your directories like this:</p>
<pre><code>folder_on_path/
com/
__init__.py
domain1/
module.py
__init__.py
other_folder_on_path/
com/
__init__.py
domain2/
module.py
__init__.py
</code></pre>
<p>Then try:</p>
<pre><code>from com.domain1 import module
from com.domain2 import module
</code></pre>
<p>Exactly one of those statements will succeed. Why? Because either <code>folder_on_path</code> or <code>other_folder_on_path</code> comes higher on the search path. When python sees <code>from com.</code> it grabs the first <code>com</code> package it can. If that happens to contain <code>domain1</code>, then the first <code>import</code> will succeed; if not, it throws an <code>ImportError</code> and gives up. Why? Because <code>import</code> must occur at runtime, potentially at any point in the flow of the code (although most often at the beginning). Nobody wants an exhaustive tree-walk at that point to verify that there's no possible match. It assumes that if it finds a package named <code>com</code>, it is <em>the</em> <code>com</code> package.</p>
<p>Moreover, python doesn't distinguish between the following statements:</p>
<pre><code>from com import domain1
from com.domain1 import module
from com.domain1.module import variable
</code></pre>
<p>The concept of verifying that <code>com</code> is <em>the</em> <code>com</code> is going to be different in each case. In java, you really only have to deal with the second case, and that can be accomplished by walking through the file system (I guess an advantage of naming classes and files the same). In python, if you tried to accomplish import with nothing but file system assistance, the first case could (almost) be transparently the same (<strong>init</strong>.py wouldn't run), the second case could be accomplished, but you would lose the initial running of module.py, but the third case is entirely unattainable. The code has to execute for <code>variable</code> to be available. And this is another main point: <code>import</code> does more than resolve namespaces, it executes code.</p>
<p>Now, you <em>could</em> get away with this if every python package ever distributed required an installation process that searched for the <code>com</code> folder, and then the <code>domain</code>, and so on and so on, but this makes packaging considerably harder, destroys drag-and-drop capability, and makes packaging and all-out nuisance.</p>
| 12
|
2009-04-02T20:05:02Z
|
[
"java",
"python",
"packages"
] |
Why do languages like Java use hierarchical package names, while Python does not?
| 709,036
|
<p>I haven't done enterprise work in Java, but I often see the <a href="http://stackoverflow.com/questions/420945/java-package-name-convention-failure">reverse-domain-name package naming convention</a>. For example, for a Stack Overflow Java package you'd put your code underneath package <code>com.stackoverflow</code>.</p>
<p>I just ran across a Python package that uses the Java-like convention, and I wasn't sure what the arguments for and against it are, or whether they apply to Python in the same way as Java. What are the reasons you'd prefer one over the other? <strong>Do those reasons apply across the languages?</strong></p>
| 13
|
2009-04-02T09:45:13Z
| 711,452
|
<p>Somewhere on Joel on Software, Joel has a comparison between two methods of growing a company: the Ben & Jerry's method, which starts small and grows organically, and the Amazon method of raising a whole lot of money and staking very wide claims from the start.</p>
<p>When Sun introduced Java, it was with fanfare and hype. Java was supposed to take over. Most future relevant software development would be on web-delivered Java applets. There would be brass bands and even ponies. In this context, it was sensible to establish, up front, a naming convention that was internet-based, corporation-friendly, and on a planetary scale.</p>
<p>OK, it didn't turn out quite as Sun hoped, but they planned as if they would succeed. Personally, I despise projects that can be undermined by success.</p>
<p>Python was a project by Guido van Rossum initially, and it was quite some time before the community was confident it would survive if van Rossum was hit by a bus. There were, as far as I know, no initial plans to take over the world, and it was not intended as a web applet language.</p>
<p>Therefore, during the formative stages of the language, there was no reason to want a vast hierarchy for a naming scheme. In that more informal community, one selected a more or less whimsical project name and checked to see if somebody else was already using it. (Naming a computer language after a British comedy show might be considered whimsical just to start.) There was no perceived need to cater to a big but unimaginative and clumsy naming scheme.</p>
| 10
|
2009-04-02T20:24:06Z
|
[
"java",
"python",
"packages"
] |
How to tell the difference between an iterator and an iterable?
| 709,084
|
<p>In Python the interface of an iterable is a subset of the <a href="http://docs.python.org/library/stdtypes.html#iterator-types">iterator interface</a>. This has the advantage that in many cases they can be treated in the same way. However, there is an important semantic difference between the two, since for an iterable <code>__iter__</code> returns a new iterator object and not just <code>self</code>. How can I test that an iterable is really an iterable and not an iterator? Conceptually I understand iterables to be collections, while an iterator only manages the iteration (i.e. keeps track of the position) but is not a collection itself.</p>
<p>The difference is for example important when one wants to loop multiple times. If an iterator is given then the second loop will not work since the iterator was already used up and directly raises <code>StopIteration</code>.</p>
<p>It is tempting to test for a <code>next</code> method, but this seems dangerous and somehow wrong. Should I just check that the second loop was empty?</p>
<p>Is there any way to do such a test in a more pythonic way? I know that this sound like a classic case of LBYL against EAFP, so maybe I should just give up? Or am I missing something?</p>
<p><strong>Edit:</strong>
S.Lott says in his answer below that this is primarily a problem of wanting to do multiple passes over the iterator, and that one should not do this in the first place. However, in my case the data is very large and depending on the situation has to be passed over multiple times for data processing (there is absolutely no way around this).</p>
<p>The iterable is also provided by the user, and for situations where a single pass is enough it will work with an iterator (e.g. created by a generator for simplicity). But it would be nice to safeguard against the case were a user provides only an iterator when multiple passes are needed.</p>
<p><strong>Edit 2:</strong>
Actually this is a very nice Example for <a href="http://www.python.org/dev/peps/pep-3119/#abcs-for-containers-and-iterators">Abstract Base Classes</a>. The <code>__iter__</code> methods in an iterator and an iterable have the same name but are sematically different! So <code>hasattr</code> is useless, but <code>isinstance</code> provides a clean solution.</p>
| 10
|
2009-04-02T09:56:55Z
| 709,123
|
<blockquote>
<p>However, there is an important semantic difference between the two...</p>
</blockquote>
<p>Not really semantic or important. They're both iterable -- they both work with a for statement.</p>
<blockquote>
<p>The difference is for example important when one wants to loop multiple times.</p>
</blockquote>
<p>When does this ever come up? You'll have to be more specific. In the rare cases when you need to make two passes through an iterable collection, there are often better algorithms.</p>
<p>For example, let's say you're processing a list. You can iterate through a list all you want. Why did you get tangled up with an iterator instead of the iterable? Okay that didn't work.</p>
<p>Okay, here's one. You're reading a file in two passes, and you need to know how to reset the iterable. In this case, it's a file, and <code>seek</code> is required; or a close and a reopen. That feels icky. You can <code>readlines</code> to get a list which allows two passes with no complexity. So that's not necessary.</p>
<p>Wait, what if we have a file so big we can't read it all into memory? And, for obscure reasons, we can't seek, either. What then?</p>
<p>Now, we're down to the nitty-gritty of two passes. On the first pass, we accumulated something. An index or a summary or something. An index has all the file's data. A summary, often, is a restructuring of the data. With a small change from "summary" to "restructure", we've preserved the file's data in the new structure. In both cases, we don't need the file -- we can use the index or the summary.</p>
<p>All "two-pass" algorithms can be changed to one pass of the original iterator or iterable and a second pass of a different data structure.</p>
<p>This is neither LYBL or EAFP. This is algorithm design. You don't need to reset an iterator -- YAGNI. </p>
<hr>
<p><strong>Edit</strong></p>
<p>Here's an example of an iterator/iterable issue. It's simply a poorly-designed algorithm.</p>
<pre><code>it = iter(xrange(3))
for i in it: print i,; #prints 1,2,3
for i in it: print i,; #prints nothing
</code></pre>
<p>This is trivially fixed.</p>
<pre><code>it = range(3)
for i in it: print i
for i in it: print i
</code></pre>
<p>The "multiple times in parallel" is trivially fixed. Write an API that <em>requires</em> an iterable. And when someone refuses to read the API documentation or refuses to follow it after having read it, their stuff breaks. As it should.</p>
<p>The "nice to safeguard against the case were a user provides only an iterator when multiple passes are needed" are both examples of insane people writing code that breaks our simple API.</p>
<p>If someone is insane enough to read most (but not all of the API doc) and provide an iterator when an iterable was <em>required</em>, you need to find this person and teach them (1) how to read all the API documentation and (2) follow the API documentation.</p>
<p>The "safeguard" issue isn't very realistic. These crazy programmers are remarkably rare. And in the few cases when it does arise, <em>you know who they are</em> and can help them.</p>
<hr>
<p><strong>Edit 2</strong></p>
<p>The "we have to read the same structure multiple times" algorithms are a fundamental problem.</p>
<p>Do not do this.</p>
<pre><code>for element in someBigIterable:
function1( element )
for element in someBigIterable:
function2( element )
...
</code></pre>
<p>Do this, instead.</p>
<pre><code>for element in someBigIterable:
function1( element )
function2( element )
...
</code></pre>
<p>Or, consider something like this.</p>
<pre><code>for element in someBigIterable:
for f in ( function1, function2, function3, ... ):
f( element )
</code></pre>
<p>In most cases, this kind of "pivot" of your algorithms results in a program that might be easier to optimize and might be a net improvement in performance.</p>
| 3
|
2009-04-02T10:09:59Z
|
[
"python",
"iterator"
] |
How to tell the difference between an iterator and an iterable?
| 709,084
|
<p>In Python the interface of an iterable is a subset of the <a href="http://docs.python.org/library/stdtypes.html#iterator-types">iterator interface</a>. This has the advantage that in many cases they can be treated in the same way. However, there is an important semantic difference between the two, since for an iterable <code>__iter__</code> returns a new iterator object and not just <code>self</code>. How can I test that an iterable is really an iterable and not an iterator? Conceptually I understand iterables to be collections, while an iterator only manages the iteration (i.e. keeps track of the position) but is not a collection itself.</p>
<p>The difference is for example important when one wants to loop multiple times. If an iterator is given then the second loop will not work since the iterator was already used up and directly raises <code>StopIteration</code>.</p>
<p>It is tempting to test for a <code>next</code> method, but this seems dangerous and somehow wrong. Should I just check that the second loop was empty?</p>
<p>Is there any way to do such a test in a more pythonic way? I know that this sound like a classic case of LBYL against EAFP, so maybe I should just give up? Or am I missing something?</p>
<p><strong>Edit:</strong>
S.Lott says in his answer below that this is primarily a problem of wanting to do multiple passes over the iterator, and that one should not do this in the first place. However, in my case the data is very large and depending on the situation has to be passed over multiple times for data processing (there is absolutely no way around this).</p>
<p>The iterable is also provided by the user, and for situations where a single pass is enough it will work with an iterator (e.g. created by a generator for simplicity). But it would be nice to safeguard against the case were a user provides only an iterator when multiple passes are needed.</p>
<p><strong>Edit 2:</strong>
Actually this is a very nice Example for <a href="http://www.python.org/dev/peps/pep-3119/#abcs-for-containers-and-iterators">Abstract Base Classes</a>. The <code>__iter__</code> methods in an iterator and an iterable have the same name but are sematically different! So <code>hasattr</code> is useless, but <code>isinstance</code> provides a clean solution.</p>
| 10
|
2009-04-02T09:56:55Z
| 709,132
|
<pre><code>'iterator' if obj is iter(obj) else 'iterable'
</code></pre>
| 14
|
2009-04-02T10:11:29Z
|
[
"python",
"iterator"
] |
How to tell the difference between an iterator and an iterable?
| 709,084
|
<p>In Python the interface of an iterable is a subset of the <a href="http://docs.python.org/library/stdtypes.html#iterator-types">iterator interface</a>. This has the advantage that in many cases they can be treated in the same way. However, there is an important semantic difference between the two, since for an iterable <code>__iter__</code> returns a new iterator object and not just <code>self</code>. How can I test that an iterable is really an iterable and not an iterator? Conceptually I understand iterables to be collections, while an iterator only manages the iteration (i.e. keeps track of the position) but is not a collection itself.</p>
<p>The difference is for example important when one wants to loop multiple times. If an iterator is given then the second loop will not work since the iterator was already used up and directly raises <code>StopIteration</code>.</p>
<p>It is tempting to test for a <code>next</code> method, but this seems dangerous and somehow wrong. Should I just check that the second loop was empty?</p>
<p>Is there any way to do such a test in a more pythonic way? I know that this sound like a classic case of LBYL against EAFP, so maybe I should just give up? Or am I missing something?</p>
<p><strong>Edit:</strong>
S.Lott says in his answer below that this is primarily a problem of wanting to do multiple passes over the iterator, and that one should not do this in the first place. However, in my case the data is very large and depending on the situation has to be passed over multiple times for data processing (there is absolutely no way around this).</p>
<p>The iterable is also provided by the user, and for situations where a single pass is enough it will work with an iterator (e.g. created by a generator for simplicity). But it would be nice to safeguard against the case were a user provides only an iterator when multiple passes are needed.</p>
<p><strong>Edit 2:</strong>
Actually this is a very nice Example for <a href="http://www.python.org/dev/peps/pep-3119/#abcs-for-containers-and-iterators">Abstract Base Classes</a>. The <code>__iter__</code> methods in an iterator and an iterable have the same name but are sematically different! So <code>hasattr</code> is useless, but <code>isinstance</code> provides a clean solution.</p>
| 10
|
2009-04-02T09:56:55Z
| 709,386
|
<p>Because of Python's duck typing, </p>
<p>Any object is iterable if it defines the <code>next()</code> and <code>__iter__()</code> method returns itself.</p>
<p>If the object itself doesnt have the <code>next()</code> method, the <code>__iter__()</code> can return any object, that has a <code>next()</code> method</p>
<p>You could refer this question to see <a href="http://stackoverflow.com/questions/649549/iterability-in-python">Iterability in Python</a></p>
| 0
|
2009-04-02T11:50:17Z
|
[
"python",
"iterator"
] |
How to tell the difference between an iterator and an iterable?
| 709,084
|
<p>In Python the interface of an iterable is a subset of the <a href="http://docs.python.org/library/stdtypes.html#iterator-types">iterator interface</a>. This has the advantage that in many cases they can be treated in the same way. However, there is an important semantic difference between the two, since for an iterable <code>__iter__</code> returns a new iterator object and not just <code>self</code>. How can I test that an iterable is really an iterable and not an iterator? Conceptually I understand iterables to be collections, while an iterator only manages the iteration (i.e. keeps track of the position) but is not a collection itself.</p>
<p>The difference is for example important when one wants to loop multiple times. If an iterator is given then the second loop will not work since the iterator was already used up and directly raises <code>StopIteration</code>.</p>
<p>It is tempting to test for a <code>next</code> method, but this seems dangerous and somehow wrong. Should I just check that the second loop was empty?</p>
<p>Is there any way to do such a test in a more pythonic way? I know that this sound like a classic case of LBYL against EAFP, so maybe I should just give up? Or am I missing something?</p>
<p><strong>Edit:</strong>
S.Lott says in his answer below that this is primarily a problem of wanting to do multiple passes over the iterator, and that one should not do this in the first place. However, in my case the data is very large and depending on the situation has to be passed over multiple times for data processing (there is absolutely no way around this).</p>
<p>The iterable is also provided by the user, and for situations where a single pass is enough it will work with an iterator (e.g. created by a generator for simplicity). But it would be nice to safeguard against the case were a user provides only an iterator when multiple passes are needed.</p>
<p><strong>Edit 2:</strong>
Actually this is a very nice Example for <a href="http://www.python.org/dev/peps/pep-3119/#abcs-for-containers-and-iterators">Abstract Base Classes</a>. The <code>__iter__</code> methods in an iterator and an iterable have the same name but are sematically different! So <code>hasattr</code> is useless, but <code>isinstance</code> provides a clean solution.</p>
| 10
|
2009-04-02T09:56:55Z
| 712,013
|
<pre><code>import itertools
def process(iterable):
work_iter, backup_iter= itertools.tee(iterable)
for item in work_iter:
# bla bla
if need_to_startover():
for another_item in backup_iter:
</code></pre>
<p>That damn time machine that Raymond borrowed from Guidoâ¦</p>
| 2
|
2009-04-02T23:24:19Z
|
[
"python",
"iterator"
] |
What is the best way to toggle python prints?
| 709,385
|
<p>I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build.
It's also imperative that it's as transparent as possible.</p>
<p>My solution to this in the C code of the engine is having the <code>printf</code> function inside a <code>vararg</code> macro, and defining that to do nothing in a release build.</p>
<p>This is my current solution:</p>
<pre><code>DebugPrints = True
def PRINT (*args):
global DebugPrints
if DebugPrints:
string = ""
for arg in args:
string += " " + str(arg)
print string
</code></pre>
<p>It makes it easy to toggle print outs, but there is possibly a better way to format the string. My main issue is that this is actually adding a lot more function calls to the program.</p>
<p>I'm wondering if there is anything you can do to how the print keyword works?</p>
| 8
|
2009-04-02T11:49:09Z
| 709,389
|
<p>yes, you can assign <code>sys.stdout</code> to whatever you want. Create a little class with a <code>write</code> method that does nothing:</p>
<pre><code>class DevNull(object):
def write(self, arg):
pass
import sys
sys.stdout = DevNull()
print "this goes to nirvana!"
</code></pre>
<p>With the same technique you can also have your prints logged to a file by setting <code>sys.stdout</code> to an opened file object.</p>
| 12
|
2009-04-02T11:50:52Z
|
[
"python",
"printing"
] |
What is the best way to toggle python prints?
| 709,385
|
<p>I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build.
It's also imperative that it's as transparent as possible.</p>
<p>My solution to this in the C code of the engine is having the <code>printf</code> function inside a <code>vararg</code> macro, and defining that to do nothing in a release build.</p>
<p>This is my current solution:</p>
<pre><code>DebugPrints = True
def PRINT (*args):
global DebugPrints
if DebugPrints:
string = ""
for arg in args:
string += " " + str(arg)
print string
</code></pre>
<p>It makes it easy to toggle print outs, but there is possibly a better way to format the string. My main issue is that this is actually adding a lot more function calls to the program.</p>
<p>I'm wondering if there is anything you can do to how the print keyword works?</p>
| 8
|
2009-04-02T11:49:09Z
| 709,393
|
<p>Don't use print, but make a console class which handles all printing. Simply make calls to the console and the console can decide whether or not to actually print them. A console class is also useful for things like error and warning messages or redirecting where the output goes.</p>
| 3
|
2009-04-02T11:52:12Z
|
[
"python",
"printing"
] |
What is the best way to toggle python prints?
| 709,385
|
<p>I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build.
It's also imperative that it's as transparent as possible.</p>
<p>My solution to this in the C code of the engine is having the <code>printf</code> function inside a <code>vararg</code> macro, and defining that to do nothing in a release build.</p>
<p>This is my current solution:</p>
<pre><code>DebugPrints = True
def PRINT (*args):
global DebugPrints
if DebugPrints:
string = ""
for arg in args:
string += " " + str(arg)
print string
</code></pre>
<p>It makes it easy to toggle print outs, but there is possibly a better way to format the string. My main issue is that this is actually adding a lot more function calls to the program.</p>
<p>I'm wondering if there is anything you can do to how the print keyword works?</p>
| 8
|
2009-04-02T11:49:09Z
| 709,417
|
<p>The <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging module</a> is the "best" way.. although I quite often just use something simple like..</p>
<pre><code>class MyLogger:
def _displayMessage(self, message, level = None):
# This can be modified easily
if level is not None:
print "[%s] %s" % (level, message
else:
print "[default] %s" % (message)
def debug(self, message):
self._displayMessage(message, level = "debug")
def info(self, message):
self._displayMessage(message, level = "info")
log = MyLogger()
log.info("test")
</code></pre>
| 8
|
2009-04-02T12:00:43Z
|
[
"python",
"printing"
] |
What is the best way to toggle python prints?
| 709,385
|
<p>I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build.
It's also imperative that it's as transparent as possible.</p>
<p>My solution to this in the C code of the engine is having the <code>printf</code> function inside a <code>vararg</code> macro, and defining that to do nothing in a release build.</p>
<p>This is my current solution:</p>
<pre><code>DebugPrints = True
def PRINT (*args):
global DebugPrints
if DebugPrints:
string = ""
for arg in args:
string += " " + str(arg)
print string
</code></pre>
<p>It makes it easy to toggle print outs, but there is possibly a better way to format the string. My main issue is that this is actually adding a lot more function calls to the program.</p>
<p>I'm wondering if there is anything you can do to how the print keyword works?</p>
| 8
|
2009-04-02T11:49:09Z
| 709,897
|
<p>I know an answer has already been marked as correct, but Python has a debug flag that provides a cleaner solution. You use it like this:</p>
<pre><code>if __debug__:
print "whoa"
</code></pre>
<p>If you invoke Python with -O or -OO (as you normally would for a release build), <code>__debug__</code> is set to <code>False</code>. What's even better is that <code>__debug__</code> is a special case for the interpreter; it will actually strip out that code when it writes the <code>pyc/pyo</code> files, making the resulting code smaller/faster. Note that you can't assign values to <code>__debug__</code>, so it's entirely based off those command-line arguments.</p>
| 10
|
2009-04-02T14:17:17Z
|
[
"python",
"printing"
] |
What is the best way to toggle python prints?
| 709,385
|
<p>I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build.
It's also imperative that it's as transparent as possible.</p>
<p>My solution to this in the C code of the engine is having the <code>printf</code> function inside a <code>vararg</code> macro, and defining that to do nothing in a release build.</p>
<p>This is my current solution:</p>
<pre><code>DebugPrints = True
def PRINT (*args):
global DebugPrints
if DebugPrints:
string = ""
for arg in args:
string += " " + str(arg)
print string
</code></pre>
<p>It makes it easy to toggle print outs, but there is possibly a better way to format the string. My main issue is that this is actually adding a lot more function calls to the program.</p>
<p>I'm wondering if there is anything you can do to how the print keyword works?</p>
| 8
|
2009-04-02T11:49:09Z
| 32,488,369
|
<p>I've answered this question on a <a href="http://stackoverflow.com/questions/32487941/efficient-way-of-toggling-on-off-print-statements-in-python/32488016#32488016">different post</a> but was the question was marked duplicate:</p>
<p>anyhow, here's what I would do:</p>
<pre><code>from __future__ import print_function
DebugPrints = 0
def print(*args, **kwargs):
if DebugPrints:
return __builtins__.print(*args, **kwargs)
print('foo') # doesn't get printed
DebugPrints = 1
print('bar') # gets printed
</code></pre>
<p>sadly you can't keep the py2 print syntax <code>print 'foo'</code></p>
| 0
|
2015-09-09T20:14:24Z
|
[
"python",
"printing"
] |
What is the best way to toggle python prints?
| 709,385
|
<p>I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build.
It's also imperative that it's as transparent as possible.</p>
<p>My solution to this in the C code of the engine is having the <code>printf</code> function inside a <code>vararg</code> macro, and defining that to do nothing in a release build.</p>
<p>This is my current solution:</p>
<pre><code>DebugPrints = True
def PRINT (*args):
global DebugPrints
if DebugPrints:
string = ""
for arg in args:
string += " " + str(arg)
print string
</code></pre>
<p>It makes it easy to toggle print outs, but there is possibly a better way to format the string. My main issue is that this is actually adding a lot more function calls to the program.</p>
<p>I'm wondering if there is anything you can do to how the print keyword works?</p>
| 8
|
2009-04-02T11:49:09Z
| 32,489,099
|
<p>If you really want to toggle printing:</p>
<pre><code>>>> import sys
>>> import os
>>> print 'foo'
foo
>>> origstdout = sys.stdout
>>> sys.stdout = open(os.devnull, 'w')
>>> print 'foo'
>>> sys.stdout = origstdout
>>> print 'foo'
foo
</code></pre>
<p>However, I recommend you only use <code>print</code> for throwaway code. Use <code>logging</code> for real apps like the original question describes. It allows for a sliding scale of verbosity, so you can have only the important logging, or more verbose logging of usually less important details.</p>
<pre><code>>>> import logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> logging.debug('foo')
DEBUG:root:foo
</code></pre>
<p>For example, usage might be to put debugging logs throughout your code. Then to silence them, change your level to a higher level, one of <code>INFO</code>, <code>WARN</code> or <code>WARNING</code>, <code>ERROR</code>, or <code>CRITICAL</code> or <code>FATAL</code></p>
<pre><code>>>> logging.root.setLevel(logging.INFO)
>>> logging.debug('foo')
>>>
</code></pre>
<p>In a script you'll want to just set this in the <code>basicConfig</code> like this:</p>
<pre><code>import logging
logging.basicConfig(level=logging.INFO)
logging.debug('foo') # this will be silent
</code></pre>
<p>More sophisticated usage of logging can be found <a href="https://docs.python.org/library/logging.html" rel="nofollow">in the docs</a>.</p>
<hr>
| 1
|
2015-09-09T21:01:21Z
|
[
"python",
"printing"
] |
What's a more elegant rephrasing of this cropping algorithm? (in Python)
| 709,388
|
<p>I want to crop a thumbnail image in my Django application, so that I get a quadratic image that shows the center of the image. This is not very hard, I agree. </p>
<p>I have already written some code that does exactly this, but somehow it lacks a certain ... elegance. I don't want to play code golf, but there must be a way to express this shorter and more pythonic, I think.</p>
<pre><code>x = y = 200 # intended size
image = Image.open(filename)
width = image.size[0]
height = image.size[1]
if (width > height):
crop_box = ( ((width - height)/2), 0, ((width - height)/2)+height, height )
image = image.crop(crop_box)
elif (height > width):
crop_box = ( 0, ((height - width)/2), width, ((height - width)/2)+width )
image = image.crop(crop_box)
image.thumbnail([x, y], Image.ANTIALIAS)
</code></pre>
<p>Do you have any ideas, SO?</p>
<p><strong>edit:</strong> explained x, y</p>
| 4
|
2009-04-02T11:50:49Z
| 709,401
|
<pre><code>width, height = image.size
if width > height:
crop_box = # something 1
else:
crop_box = # something 2
image = image.crop(crop_box)
image.thumbnail([x, x], Image.ANTIALIAS) # explicitly show "square" thumbnail
</code></pre>
| 1
|
2009-04-02T11:56:26Z
|
[
"image",
"python-imaging-library",
"python",
"crop"
] |
What's a more elegant rephrasing of this cropping algorithm? (in Python)
| 709,388
|
<p>I want to crop a thumbnail image in my Django application, so that I get a quadratic image that shows the center of the image. This is not very hard, I agree. </p>
<p>I have already written some code that does exactly this, but somehow it lacks a certain ... elegance. I don't want to play code golf, but there must be a way to express this shorter and more pythonic, I think.</p>
<pre><code>x = y = 200 # intended size
image = Image.open(filename)
width = image.size[0]
height = image.size[1]
if (width > height):
crop_box = ( ((width - height)/2), 0, ((width - height)/2)+height, height )
image = image.crop(crop_box)
elif (height > width):
crop_box = ( 0, ((height - width)/2), width, ((height - width)/2)+width )
image = image.crop(crop_box)
image.thumbnail([x, y], Image.ANTIALIAS)
</code></pre>
<p>Do you have any ideas, SO?</p>
<p><strong>edit:</strong> explained x, y</p>
| 4
|
2009-04-02T11:50:49Z
| 709,437
|
<p>The <code>fit()</code> function in the PIL <a href="http://www.pythonware.com/library/pil/handbook/imageops.htm" rel="nofollow">ImageOps</a> module does what you want:</p>
<pre><code>ImageOps.fit(image, (min(*image.size),) * 2, Image.ANTIALIAS, 0, (.5, .5))
</code></pre>
| 6
|
2009-04-02T12:05:43Z
|
[
"image",
"python-imaging-library",
"python",
"crop"
] |
What's a more elegant rephrasing of this cropping algorithm? (in Python)
| 709,388
|
<p>I want to crop a thumbnail image in my Django application, so that I get a quadratic image that shows the center of the image. This is not very hard, I agree. </p>
<p>I have already written some code that does exactly this, but somehow it lacks a certain ... elegance. I don't want to play code golf, but there must be a way to express this shorter and more pythonic, I think.</p>
<pre><code>x = y = 200 # intended size
image = Image.open(filename)
width = image.size[0]
height = image.size[1]
if (width > height):
crop_box = ( ((width - height)/2), 0, ((width - height)/2)+height, height )
image = image.crop(crop_box)
elif (height > width):
crop_box = ( 0, ((height - width)/2), width, ((height - width)/2)+width )
image = image.crop(crop_box)
image.thumbnail([x, y], Image.ANTIALIAS)
</code></pre>
<p>Do you have any ideas, SO?</p>
<p><strong>edit:</strong> explained x, y</p>
| 4
|
2009-04-02T11:50:49Z
| 709,442
|
<p>I think this should do.</p>
<pre><code>size = min(image.Size)
originX = image.Size[0] / 2 - size / 2
originY = image.Size[1] / 2 - size / 2
cropBox = (originX, originY, originX + size, originY + size)
</code></pre>
| 9
|
2009-04-02T12:06:23Z
|
[
"image",
"python-imaging-library",
"python",
"crop"
] |
What's a more elegant rephrasing of this cropping algorithm? (in Python)
| 709,388
|
<p>I want to crop a thumbnail image in my Django application, so that I get a quadratic image that shows the center of the image. This is not very hard, I agree. </p>
<p>I have already written some code that does exactly this, but somehow it lacks a certain ... elegance. I don't want to play code golf, but there must be a way to express this shorter and more pythonic, I think.</p>
<pre><code>x = y = 200 # intended size
image = Image.open(filename)
width = image.size[0]
height = image.size[1]
if (width > height):
crop_box = ( ((width - height)/2), 0, ((width - height)/2)+height, height )
image = image.crop(crop_box)
elif (height > width):
crop_box = ( 0, ((height - width)/2), width, ((height - width)/2)+width )
image = image.crop(crop_box)
image.thumbnail([x, y], Image.ANTIALIAS)
</code></pre>
<p>Do you have any ideas, SO?</p>
<p><strong>edit:</strong> explained x, y</p>
| 4
|
2009-04-02T11:50:49Z
| 1,320,073
|
<p>I want to a content analysis of a jepg image. I wish to take a jpeg imafe say 251 x 261 and pass it through an algorithm to crop it to say 96 x 87. Can this program do that like t write an intelligent cropping algorithm, with a prompt to rezie the image.</p>
| 0
|
2009-08-24T01:14:21Z
|
[
"image",
"python-imaging-library",
"python",
"crop"
] |
Import an existing python project to XCode
| 709,397
|
<p>I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository.</p>
<p>Other developers are working on the project not using XCode - They won't mind if I add a project file or something, but they will mind if I have to reorganise the whole thing.</p>
| 6
|
2009-04-02T11:54:59Z
| 710,629
|
<p>I don't think it's worth using Xcode for a pure python project. Although the Xcode editor does syntax-highlight Python code, Xcode does not give you any other benefit for writing a pure-python app. On OS X, I would recommend <a href="http://macromates.com/" rel="nofollow">TextMate</a> as a text editor or Eclipse with <a href="http://pydev.sourceforge.net/" rel="nofollow">PyDev</a> as a more full-featured IDE.</p>
| 7
|
2009-04-02T16:57:19Z
|
[
"python",
"xcode",
"osx"
] |
Import an existing python project to XCode
| 709,397
|
<p>I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository.</p>
<p>Other developers are working on the project not using XCode - They won't mind if I add a project file or something, but they will mind if I have to reorganise the whole thing.</p>
| 6
|
2009-04-02T11:54:59Z
| 851,810
|
<p>There are no special facilities for working with non-Cocoa Python projects with Xcode. Therefore, you probably just want to create a project with the "Empty Project" template (under "Other") and just drag in your source code.</p>
<p>For convenience, you may want to set up an executable in the project. You can do this by ctrl/right-clicking in the project source list and choosing "Add" > "New Custom Executable...". You can also add a target, although I'm not sure what this would buy you.</p>
| 1
|
2009-05-12T08:50:30Z
|
[
"python",
"xcode",
"osx"
] |
Import an existing python project to XCode
| 709,397
|
<p>I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository.</p>
<p>Other developers are working on the project not using XCode - They won't mind if I add a project file or something, but they will mind if I have to reorganise the whole thing.</p>
| 6
|
2009-04-02T11:54:59Z
| 851,861
|
<p>I recommend against doing so. Creating groups (which look like folders) in Xcode doesn't actually create folders in the filesystem. This wreaks havoc on the module hierarchy.</p>
<p>Also, the SCM integration in Xcode is very clunky. After becoming accustomed to using Subversion with Eclipse, the Subversion support in Xcode is hopelessly primitive. It's almost easier to just do svn commands on the command line just so it's clear what's going on.</p>
<p>If you must use Xcode, use it to open individual <code>py</code> files. Use it as a slow, relatively featureless text editor.</p>
<p>If you must use Xcode for SCM, take a look at their <a href="http://developer.apple.com/tools/subversionxcode.html" rel="nofollow">guide to using Xcode with Subversion</a>.</p>
| 2
|
2009-05-12T09:02:38Z
|
[
"python",
"xcode",
"osx"
] |
Import an existing python project to XCode
| 709,397
|
<p>I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository.</p>
<p>Other developers are working on the project not using XCode - They won't mind if I add a project file or something, but they will mind if I have to reorganise the whole thing.</p>
| 6
|
2009-04-02T11:54:59Z
| 4,152,716
|
<p>Also see:</p>
<p><a href="http://lethain.com/entry/2008/aug/22/an-epic-introduction-to-pyobjc-and-cocoa/" rel="nofollow">http://lethain.com/entry/2008/aug/22/an-epic-introduction-to-pyobjc-and-cocoa/</a></p>
| 1
|
2010-11-11T08:56:55Z
|
[
"python",
"xcode",
"osx"
] |
python code convention using pylint
| 709,490
|
<p>I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (<code>const-rgx</code>) instead of the variable name regex (<code>variable-rgx</code>). How to match the variable name with <code>variable-rgx</code>? Or should I extend <code>const-rgx</code> with my <code>variable-rgx</code> stuff?</p>
<p>e.g.<br />
<code>C0103: 31: Invalid name "settings" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)</code></p>
| 9
|
2009-04-02T12:21:31Z
| 709,515
|
<p>I just disable that warning because I don't follow those naming conventions.</p>
<p>To do that, add this line to the top of you module:</p>
<pre><code># pylint: disable-msg=C0103
</code></pre>
<p>If you want to disable that globally, then add it to the pylint command:</p>
<pre><code>python lint.py --disable-msg=C0103 ...
</code></pre>
| 9
|
2009-04-02T12:29:00Z
|
[
"python",
"conventions",
"pylint"
] |
python code convention using pylint
| 709,490
|
<p>I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (<code>const-rgx</code>) instead of the variable name regex (<code>variable-rgx</code>). How to match the variable name with <code>variable-rgx</code>? Or should I extend <code>const-rgx</code> with my <code>variable-rgx</code> stuff?</p>
<p>e.g.<br />
<code>C0103: 31: Invalid name "settings" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)</code></p>
| 9
|
2009-04-02T12:21:31Z
| 709,666
|
<pre><code>
(should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)
</code></pre>
<p>like you said that is the const-rgx that is only matching UPPERCASE names, or names surrounded by double underscores.</p>
<p>the variables-rgx is </p>
<pre><code>([a-z_][a-z0-9_]{2,30}$)</code></pre>
<p>if your variable is called 'settings' that indeed should match the variables-rgx</p>
<p>I can think of only 2 reasons for this..
either settings is a <strong>constant</strong> or it is a bug in PyLint.</p>
| 0
|
2009-04-02T13:18:58Z
|
[
"python",
"conventions",
"pylint"
] |
python code convention using pylint
| 709,490
|
<p>I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (<code>const-rgx</code>) instead of the variable name regex (<code>variable-rgx</code>). How to match the variable name with <code>variable-rgx</code>? Or should I extend <code>const-rgx</code> with my <code>variable-rgx</code> stuff?</p>
<p>e.g.<br />
<code>C0103: 31: Invalid name "settings" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)</code></p>
| 9
|
2009-04-02T12:21:31Z
| 709,709
|
<blockquote>
<p>Somehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx).</p>
</blockquote>
<p>Are those variables declared on module level? Maybe that's why they are treated as constants (at least that's how they should be declared, according to PEP-8).</p>
| 24
|
2009-04-02T13:27:59Z
|
[
"python",
"conventions",
"pylint"
] |
Python server side AJAX library?
| 709,868
|
<p>I want to have a browser page that updates some information on a timer or events. I'd like to use Python on the server side. It's quite simple, I don't need anything massively complex.</p>
<p>I can spend some time figuring out how to do all this the "AJAX way", but I'm sure someone has written a nice Python library to do all the heavy lifting. If you have used such a library please let me know the details. </p>
<p>Note: I saw <a href="http://stackoverflow.com/questions/336866/how-to-implement-a-minimal-server-for-ajax-in-python">how-to-implement-a-minimal-server-for-ajax-in-python</a> but I want a library to hide the implementation details.</p>
| 5
|
2009-04-02T14:09:01Z
| 709,871
|
<p>AJAX stands for Asynchronous JavaScript and XML. You don't need any special library, other than the Javascript installed on the browser to do AJAX calls. The AJAX requests comes from the client side Javascript code, and goes to the server side which in your case would be handled in python.</p>
<p>You probably want to use the <a href="http://www.djangoproject.com/" rel="nofollow">Django web framework</a>.</p>
<p>Check out this tutorial on <a href="http://www.b-list.org/weblog/2006/jul/31/django-tips-simple-ajax-example-part-1/" rel="nofollow">Django tips: A simple AJAX example</a>. </p>
<p>Here is a <a href="http://www.mousewhisperer.co.uk/ajax%5Fpage.html" rel="nofollow">simple client side tutorial on XmlHTTPRequest / AJAX</a></p>
| 5
|
2009-04-02T14:10:03Z
|
[
"python",
"ajax"
] |
Python server side AJAX library?
| 709,868
|
<p>I want to have a browser page that updates some information on a timer or events. I'd like to use Python on the server side. It's quite simple, I don't need anything massively complex.</p>
<p>I can spend some time figuring out how to do all this the "AJAX way", but I'm sure someone has written a nice Python library to do all the heavy lifting. If you have used such a library please let me know the details. </p>
<p>Note: I saw <a href="http://stackoverflow.com/questions/336866/how-to-implement-a-minimal-server-for-ajax-in-python">how-to-implement-a-minimal-server-for-ajax-in-python</a> but I want a library to hide the implementation details.</p>
| 5
|
2009-04-02T14:09:01Z
| 709,918
|
<p>You <em>can</em> also write both the client and server side of the ajax code using python with pyjamas:</p>
<p>Here's an RPC style server and simple example:</p>
<p><a href="http://www.machine-envy.com/blog/2006/12/10/howto-pyjamas-pylons-json/" rel="nofollow">http://www.machine-envy.com/blog/2006/12/10/howto-pyjamas-pylons-json/</a></p>
<p>Lots of people use it with Django, but as the above example shows it will work fine with Pylons, and can be used with TurboGears2 just as easily. </p>
<p>I'm generally in favor of learning enough javascript to do this kind of thing yourself, but if your problem fits what pygjamas can do, you'll get results from that very quickly and easily. </p>
| 5
|
2009-04-02T14:23:17Z
|
[
"python",
"ajax"
] |
Python server side AJAX library?
| 709,868
|
<p>I want to have a browser page that updates some information on a timer or events. I'd like to use Python on the server side. It's quite simple, I don't need anything massively complex.</p>
<p>I can spend some time figuring out how to do all this the "AJAX way", but I'm sure someone has written a nice Python library to do all the heavy lifting. If you have used such a library please let me know the details. </p>
<p>Note: I saw <a href="http://stackoverflow.com/questions/336866/how-to-implement-a-minimal-server-for-ajax-in-python">how-to-implement-a-minimal-server-for-ajax-in-python</a> but I want a library to hide the implementation details.</p>
| 5
|
2009-04-02T14:09:01Z
| 710,259
|
<p>I suggest you to implement the server part in Django, which is in my opinion a fantastic toolkit. Through Django, you produce your XML responses (although I suggest you to use JSON, which is easier to handle on the web browser side).</p>
<p>Once you have something that generates your reply on server side, you have to code the javascript code that invokes it (through the asynchronous call), gets the result (in JSON) and uses it to do something clever on the DOM tree of the page. For this, you need a JavaScript library.</p>
<p>I did some experience with various javascript libraries for "Web 2.0". <a href="http://script.aculo.us/" rel="nofollow">Scriptaculous</a> is cool, and <a href="http://www.dojotoolkit.org/" rel="nofollow">Dojo</a> as well, but my absolute favourite is <a href="http://mochikit.com/" rel="nofollow">MochiKit</a>, because they focus on a syntax which is very pythonic, so it will hide you quite well the differences between javascript and python.</p>
| 1
|
2009-04-02T15:36:57Z
|
[
"python",
"ajax"
] |
Backslashes being added into my cookie in Python
| 709,937
|
<p>Hey,
I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what. Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real world. </p>
<p>Anyway, so basically I am keeping information input into a form in a cookie. I am attempting to append to the previous cookie with the new information entered. But for some reason on the third entry of data the cookie suddenly gets "\" in it. I am not sure where they are coming from though. </p>
<p>This is the type of output I am getting:</p>
<blockquote>
<p>"\"\\"\\\\"test:more\\\\":rttre\\":more\":and more"</p>
</blockquote>
<pre><code>#!/usr/local/bin/python
import cgi,os,time,Cookie
#error checking
import cgitb
cgitb.enable()
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
hideMe = value
#import critterClass
#get info from form
form = cgi.FieldStorage()
critterName = form.getvalue('input')
input2 = form.getvalue('input2')
hiddenCookie = form.getvalue('hiddenCookie')
hiddenVar = form.getvalue('hiddenVar')
#make cookie
cookie = Cookie.SimpleCookie()
#set critter Cookie
if critterName is not None:
cookie['critter'] = critterName
#If already named
else:
#if action asked, append cookie
if input2 is not None:
cookie['critter'] = hideMe+":"+input2
else:
cookie['critter'] = "default"
print cookie
print "Content-type: text/html\n\n"
if ((critterName is None) and (input2 is None)):
print """
<form name="critter" id="critter" method="post" action="critter.py">
<label for="name">Name your pet: <input type="text" name="input" id="input" /></label>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
"""
else:
formTwo ="""
<form name="critter2" id="critter2" method="post" action="critter.py">
<label for="name">%s wants to: <input type="text" name="input2" id="input2" /></label>
<input type="hidden" name="hiddenVar" id="hiddenVar" value="%s" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
[name,play,feed,mood,levels,end]
"""
print formTwo % (critterName,critterName)
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
print "name"+name
print "value"+value
</code></pre>
| 7
|
2009-04-02T14:29:22Z
| 709,980
|
<p>I'm not sure, but it looks like regular Python string escaping. If you have a string containing a backslash or a double quote, for instance, Python will often print it in escaped form, to make the printed string a valid string literal.</p>
<p>The following snippet illustrates:</p>
<pre><code>>>> a='hell\'s bells, \"my\" \\'
>>> a
'hell\'s bells, "my" \\'
>>> print a
hell's bells, "my" \
</code></pre>
<p>Not sure if this is relevant, perhaps someone with more domain knowledge can chime in.</p>
| 2
|
2009-04-02T14:41:25Z
|
[
"python"
] |
Backslashes being added into my cookie in Python
| 709,937
|
<p>Hey,
I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what. Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real world. </p>
<p>Anyway, so basically I am keeping information input into a form in a cookie. I am attempting to append to the previous cookie with the new information entered. But for some reason on the third entry of data the cookie suddenly gets "\" in it. I am not sure where they are coming from though. </p>
<p>This is the type of output I am getting:</p>
<blockquote>
<p>"\"\\"\\\\"test:more\\\\":rttre\\":more\":and more"</p>
</blockquote>
<pre><code>#!/usr/local/bin/python
import cgi,os,time,Cookie
#error checking
import cgitb
cgitb.enable()
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
hideMe = value
#import critterClass
#get info from form
form = cgi.FieldStorage()
critterName = form.getvalue('input')
input2 = form.getvalue('input2')
hiddenCookie = form.getvalue('hiddenCookie')
hiddenVar = form.getvalue('hiddenVar')
#make cookie
cookie = Cookie.SimpleCookie()
#set critter Cookie
if critterName is not None:
cookie['critter'] = critterName
#If already named
else:
#if action asked, append cookie
if input2 is not None:
cookie['critter'] = hideMe+":"+input2
else:
cookie['critter'] = "default"
print cookie
print "Content-type: text/html\n\n"
if ((critterName is None) and (input2 is None)):
print """
<form name="critter" id="critter" method="post" action="critter.py">
<label for="name">Name your pet: <input type="text" name="input" id="input" /></label>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
"""
else:
formTwo ="""
<form name="critter2" id="critter2" method="post" action="critter.py">
<label for="name">%s wants to: <input type="text" name="input2" id="input2" /></label>
<input type="hidden" name="hiddenVar" id="hiddenVar" value="%s" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
[name,play,feed,mood,levels,end]
"""
print formTwo % (critterName,critterName)
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
print "name"+name
print "value"+value
</code></pre>
| 7
|
2009-04-02T14:29:22Z
| 709,985
|
<p>The slashes result from escaping the double quotes. Apparently, the first time through, your code is seeing the double quote, and escaping it by adding a back-slash. Then it reads the escaped backslash, and escapes the backslash by prepending it with -- a backslash. Then it reads....</p>
<p>The problem is happening when you call append.</p>
| 2
|
2009-04-02T14:41:57Z
|
[
"python"
] |
Backslashes being added into my cookie in Python
| 709,937
|
<p>Hey,
I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what. Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real world. </p>
<p>Anyway, so basically I am keeping information input into a form in a cookie. I am attempting to append to the previous cookie with the new information entered. But for some reason on the third entry of data the cookie suddenly gets "\" in it. I am not sure where they are coming from though. </p>
<p>This is the type of output I am getting:</p>
<blockquote>
<p>"\"\\"\\\\"test:more\\\\":rttre\\":more\":and more"</p>
</blockquote>
<pre><code>#!/usr/local/bin/python
import cgi,os,time,Cookie
#error checking
import cgitb
cgitb.enable()
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
hideMe = value
#import critterClass
#get info from form
form = cgi.FieldStorage()
critterName = form.getvalue('input')
input2 = form.getvalue('input2')
hiddenCookie = form.getvalue('hiddenCookie')
hiddenVar = form.getvalue('hiddenVar')
#make cookie
cookie = Cookie.SimpleCookie()
#set critter Cookie
if critterName is not None:
cookie['critter'] = critterName
#If already named
else:
#if action asked, append cookie
if input2 is not None:
cookie['critter'] = hideMe+":"+input2
else:
cookie['critter'] = "default"
print cookie
print "Content-type: text/html\n\n"
if ((critterName is None) and (input2 is None)):
print """
<form name="critter" id="critter" method="post" action="critter.py">
<label for="name">Name your pet: <input type="text" name="input" id="input" /></label>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
"""
else:
formTwo ="""
<form name="critter2" id="critter2" method="post" action="critter.py">
<label for="name">%s wants to: <input type="text" name="input2" id="input2" /></label>
<input type="hidden" name="hiddenVar" id="hiddenVar" value="%s" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
[name,play,feed,mood,levels,end]
"""
print formTwo % (critterName,critterName)
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
print "name"+name
print "value"+value
</code></pre>
| 7
|
2009-04-02T14:29:22Z
| 709,986
|
<p>Backslashes are used for "escaping" characters in strings that would otherwise have special meaning, in effect depriving them of their special meaning. The classic case is the way you can include quotes in quoted strings, such as:</p>
<pre><code>Bob said "Hey!"
</code></pre>
<p>which can be written as a string this way:</p>
<pre><code>"Bob said \"Hey!\""
</code></pre>
<p>Of course, you may want to have a regular backslash in there, so "\" just means a single backslash.</p>
<p><strong>EDIT:</strong> In response to your comment on another answer (about using a regexp to remove the slashes) I think you're picking up the wrong end of the stick. The slashes aren't the problem, they are a symptom. The problem is that you're doing round trips treating strings representing quoted strings as if they were plain old strings. Imagine two friends, Bob and Sam, having a conversation:</p>
<pre><code>Bob: Hey!
Sam: Did you say "Hey!"?
Bob: Did you say "Did you say \"Hey!\"?"?
</code></pre>
<p>That's why the don't show up until the third time.</p>
| 1
|
2009-04-02T14:42:08Z
|
[
"python"
] |
Backslashes being added into my cookie in Python
| 709,937
|
<p>Hey,
I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what. Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real world. </p>
<p>Anyway, so basically I am keeping information input into a form in a cookie. I am attempting to append to the previous cookie with the new information entered. But for some reason on the third entry of data the cookie suddenly gets "\" in it. I am not sure where they are coming from though. </p>
<p>This is the type of output I am getting:</p>
<blockquote>
<p>"\"\\"\\\\"test:more\\\\":rttre\\":more\":and more"</p>
</blockquote>
<pre><code>#!/usr/local/bin/python
import cgi,os,time,Cookie
#error checking
import cgitb
cgitb.enable()
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
hideMe = value
#import critterClass
#get info from form
form = cgi.FieldStorage()
critterName = form.getvalue('input')
input2 = form.getvalue('input2')
hiddenCookie = form.getvalue('hiddenCookie')
hiddenVar = form.getvalue('hiddenVar')
#make cookie
cookie = Cookie.SimpleCookie()
#set critter Cookie
if critterName is not None:
cookie['critter'] = critterName
#If already named
else:
#if action asked, append cookie
if input2 is not None:
cookie['critter'] = hideMe+":"+input2
else:
cookie['critter'] = "default"
print cookie
print "Content-type: text/html\n\n"
if ((critterName is None) and (input2 is None)):
print """
<form name="critter" id="critter" method="post" action="critter.py">
<label for="name">Name your pet: <input type="text" name="input" id="input" /></label>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
"""
else:
formTwo ="""
<form name="critter2" id="critter2" method="post" action="critter.py">
<label for="name">%s wants to: <input type="text" name="input2" id="input2" /></label>
<input type="hidden" name="hiddenVar" id="hiddenVar" value="%s" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
[name,play,feed,mood,levels,end]
"""
print formTwo % (critterName,critterName)
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
print "name"+name
print "value"+value
</code></pre>
| 7
|
2009-04-02T14:29:22Z
| 710,500
|
<p>As explained by others, the backslashes are escaping double quote characters you insert into the cookie value. The (hidden) mechanism in action here is the <a href="http://docs.python.org/library/cookie.html#Cookie.SimpleCookie" rel="nofollow"><code>SimpleCookie</code></a> class. The <a href="http://docs.python.org/library/cookie.html#Cookie.BaseCookie.output" rel="nofollow"><code>BaseCookie.output()</code></a> method returns a string representation suitable to be sent as HTTP headers. It will insert escape characters (backslashes) before double quote characters and <strong>before backslash characters</strong>.</p>
<p>The</p>
<pre><code>print cookie
</code></pre>
<p>statement activates <code>BaseCookie.output()</code>.</p>
<p>On each trip your string makes through the cookie's <code>output()</code> method, backslashes are multiplied (starting with the 1st pair of quotes).</p>
<pre><code>>>> c1=Cookie.SimpleCookie()
>>> c1['name']='A:0'
>>> print c1
Set-Cookie: name="A:0"
>>> c1['name']=r'"A:0"'
>>> print c1
Set-Cookie: name="\"A:0\""
>>> c1['name']=r'"\"A:0\""'
>>> print c1
Set-Cookie: name="\"\\\"A:0\\\"\""
>>>
</code></pre>
| 3
|
2009-04-02T16:28:43Z
|
[
"python"
] |
Backslashes being added into my cookie in Python
| 709,937
|
<p>Hey,
I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what. Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real world. </p>
<p>Anyway, so basically I am keeping information input into a form in a cookie. I am attempting to append to the previous cookie with the new information entered. But for some reason on the third entry of data the cookie suddenly gets "\" in it. I am not sure where they are coming from though. </p>
<p>This is the type of output I am getting:</p>
<blockquote>
<p>"\"\\"\\\\"test:more\\\\":rttre\\":more\":and more"</p>
</blockquote>
<pre><code>#!/usr/local/bin/python
import cgi,os,time,Cookie
#error checking
import cgitb
cgitb.enable()
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
hideMe = value
#import critterClass
#get info from form
form = cgi.FieldStorage()
critterName = form.getvalue('input')
input2 = form.getvalue('input2')
hiddenCookie = form.getvalue('hiddenCookie')
hiddenVar = form.getvalue('hiddenVar')
#make cookie
cookie = Cookie.SimpleCookie()
#set critter Cookie
if critterName is not None:
cookie['critter'] = critterName
#If already named
else:
#if action asked, append cookie
if input2 is not None:
cookie['critter'] = hideMe+":"+input2
else:
cookie['critter'] = "default"
print cookie
print "Content-type: text/html\n\n"
if ((critterName is None) and (input2 is None)):
print """
<form name="critter" id="critter" method="post" action="critter.py">
<label for="name">Name your pet: <input type="text" name="input" id="input" /></label>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
"""
else:
formTwo ="""
<form name="critter2" id="critter2" method="post" action="critter.py">
<label for="name">%s wants to: <input type="text" name="input2" id="input2" /></label>
<input type="hidden" name="hiddenVar" id="hiddenVar" value="%s" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
[name,play,feed,mood,levels,end]
"""
print formTwo % (critterName,critterName)
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
print "name"+name
print "value"+value
</code></pre>
| 7
|
2009-04-02T14:29:22Z
| 711,392
|
<p>As others have already said, you are experiencing string escaping issues as soon as you add "and more" onto the end of the cookie.</p>
<p>Until that point, the cookie header is being returned from the SimpleCookie without enclosing quotes. (If there are no spaces in the cookie value, then enclosing quotes are not needed.)</p>
<pre><code># HTTP cookie header with no spaces in value
Set-Cookie: cookie=value
# HTTP cookie header with spaces in value
Set-Cookie: cookie="value with spaces"
</code></pre>
<p>I would suggest using the same SimpleCookie class to parse the cookie header initially, saving you from doing it by hand, and also handling unescaping the strings properly.</p>
<pre><code>cookies = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE', ''))
print cookies['critter'].value
</code></pre>
<p><strong><em>edit</em></strong>: This whole deal with the spaces does not apply to this question (although it can in certain circumstances come and bite you when you are not expecting it.) But my suggestion to use the SimpleCookie to parse still stands.</p>
| 2
|
2009-04-02T20:07:49Z
|
[
"python"
] |
Backslashes being added into my cookie in Python
| 709,937
|
<p>Hey,
I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what. Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real world. </p>
<p>Anyway, so basically I am keeping information input into a form in a cookie. I am attempting to append to the previous cookie with the new information entered. But for some reason on the third entry of data the cookie suddenly gets "\" in it. I am not sure where they are coming from though. </p>
<p>This is the type of output I am getting:</p>
<blockquote>
<p>"\"\\"\\\\"test:more\\\\":rttre\\":more\":and more"</p>
</blockquote>
<pre><code>#!/usr/local/bin/python
import cgi,os,time,Cookie
#error checking
import cgitb
cgitb.enable()
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
hideMe = value
#import critterClass
#get info from form
form = cgi.FieldStorage()
critterName = form.getvalue('input')
input2 = form.getvalue('input2')
hiddenCookie = form.getvalue('hiddenCookie')
hiddenVar = form.getvalue('hiddenVar')
#make cookie
cookie = Cookie.SimpleCookie()
#set critter Cookie
if critterName is not None:
cookie['critter'] = critterName
#If already named
else:
#if action asked, append cookie
if input2 is not None:
cookie['critter'] = hideMe+":"+input2
else:
cookie['critter'] = "default"
print cookie
print "Content-type: text/html\n\n"
if ((critterName is None) and (input2 is None)):
print """
<form name="critter" id="critter" method="post" action="critter.py">
<label for="name">Name your pet: <input type="text" name="input" id="input" /></label>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
"""
else:
formTwo ="""
<form name="critter2" id="critter2" method="post" action="critter.py">
<label for="name">%s wants to: <input type="text" name="input2" id="input2" /></label>
<input type="hidden" name="hiddenVar" id="hiddenVar" value="%s" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
[name,play,feed,mood,levels,end]
"""
print formTwo % (critterName,critterName)
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
for myCookie in cookies:
myCookie = myCookie.split('=')
name = myCookie[0]
value = myCookie[1]
if name == 'critter' :
print "name"+name
print "value"+value
</code></pre>
| 7
|
2009-04-02T14:29:22Z
| 712,178
|
<p>Others have already pointed out that this is a result of backslash-escapes of quotes and backslashes. I just wanted to point out that if you look carefully at the structure of the output you cite, you can see how the structure is being built here.</p>
<p>The cookie value that you're getting from <code>SimpleCookie</code> is wrapped in quotes -- the (unprocessed) cookie has, e.g., </p>
<pre><code>`'[...], critter="value1", [...]'`
</code></pre>
<p>After you split on <code>', '</code> and <code>'='</code>, you have a string that contains <code>"value1"</code>. You then append a new value to that string, so that the string contains <code>"value1":value2</code>.</p>
<p>The next time through, you get that string back, but with another set of quotes wrapping it -- conceptually, <code>""value1":value2"</code>. But in order to make it so that a web browser will not see two quote characters at the beginning and think that's all there is, the inner set of quotes is being escaped, so it's actually returned as <code>"\"value1\":value2"</code>.</p>
<p>You then append yet another chunk, make another pass back and forth between server and client, and the next time (because those backslashes need escaped now too) you get <code>"\"\\"value1\\":value2\":value3"</code>. And so on.</p>
<p>The correct solution, as has already been pointed out, is to let <code>SimpleCookie</code> do the parsing instead of chopping up the strings yourself.</p>
| 1
|
2009-04-03T00:47:27Z
|
[
"python"
] |
'for' loop through form fields and excluding one of the fields with 'if'
| 710,100
|
<p>The problem I'm struggling with is as follows:</p>
<p>I have:</p>
<pre><code>{% for field in form %}
{{Â field }}
{% end for %}
</code></pre>
<p>What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like:</p>
<pre><code>{% for field in form%}
{% if field == title %}
{% else %}
{{ field }}
{% endif %}
{% endfor %}
</code></pre>
<p>Is it possible? I have to many fields to write them one by one and only one or two to exclude.</p>
<p>Thank you for any tips.</p>
<p>BR,
Czlowiekwidmo.</p>
| 3
|
2009-04-02T15:05:31Z
| 710,146
|
<p>Yes, this should be possible:</p>
<pre><code>{% for field in form %}
{% ifnotequal field.label title %}
{{ field }}
{% endifnotequal %}
{% endfor %}
</code></pre>
<p>Django's <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ref-templates-builtins">template tags</a> offer <code>ifequal</code> and <code>ifnotequal</code> variants, and you can test the field.label against either a context variable, or a string.</p>
| 7
|
2009-04-02T15:14:10Z
|
[
"python",
"django-templates"
] |
'for' loop through form fields and excluding one of the fields with 'if'
| 710,100
|
<p>The problem I'm struggling with is as follows:</p>
<p>I have:</p>
<pre><code>{% for field in form %}
{{Â field }}
{% end for %}
</code></pre>
<p>What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like:</p>
<pre><code>{% for field in form%}
{% if field == title %}
{% else %}
{{ field }}
{% endif %}
{% endfor %}
</code></pre>
<p>Is it possible? I have to many fields to write them one by one and only one or two to exclude.</p>
<p>Thank you for any tips.</p>
<p>BR,
Czlowiekwidmo.</p>
| 3
|
2009-04-02T15:05:31Z
| 710,350
|
<p>You might be a lot happier creating a subclass of the form, excluding the offending field.
See <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#form-inheritance">http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#form-inheritance</a></p>
<pre><code>class SmallerForm( MyForm ):
class Meta(MyForm.Meta):
exclude = [ title ]
</code></pre>
| 6
|
2009-04-02T15:52:51Z
|
[
"python",
"django-templates"
] |
case-insensitive alphabetical sorting of nested lists
| 710,262
|
<p>i'm trying to sort this nested list by inner's list first element:</p>
<pre><code>ak = [ ['a',1],['E',2],['C',13],['A',11],['b',9] ]
ak.sort(cmp=lambda x, y: cmp(x[0], y[0]))
for i in ak: {
print i
}
</code></pre>
<p>by default python considers A > a, hence the output i get is:</p>
<pre><code>['A', 11] ['C', 13] ['E', 2] ['a', 1] ['b', 9]
</code></pre>
<p>i've tried converting all list values to even case during comparison by adding x[0].lower etc. but no use. How do i force python (i'm working on 2.4 version) to do case-insensitive alphabetical sorting?</p>
<p><strong>Edited:</strong></p>
<blockquote>
<p>Jarret and Brian, your
assumptions about parenthesis were
right! I did forget to put them in! And Jarret, your suggestions about not using "cmp" works like a charm! Thanks a lot guys!</p>
</blockquote>
| 1
|
2009-04-02T15:37:15Z
| 710,274
|
<p>Try:</p>
<pre><code>ak.sort(key=lambda x:x[0].lower())
</code></pre>
<p>I would recommend that you avoid using <code>cmp</code> as this has been deprecated in Python 2.6, and removed in 3.0. I know you're using 2.4, but the reason <code>cmp</code> has fallen into disfavour is that it is a very slow way to sort.</p>
<p>I'm not sure why your effort with <code>lower</code> failed, though... perhaps you forgot to use the function call versus just the function name? (ie: <code>cmp(x[0].lower(), y[0].lower())</code> versus <code>cmp(x[0].lower, y[0].lower)</code>)</p>
| 9
|
2009-04-02T15:39:06Z
|
[
"python"
] |
case-insensitive alphabetical sorting of nested lists
| 710,262
|
<p>i'm trying to sort this nested list by inner's list first element:</p>
<pre><code>ak = [ ['a',1],['E',2],['C',13],['A',11],['b',9] ]
ak.sort(cmp=lambda x, y: cmp(x[0], y[0]))
for i in ak: {
print i
}
</code></pre>
<p>by default python considers A > a, hence the output i get is:</p>
<pre><code>['A', 11] ['C', 13] ['E', 2] ['a', 1] ['b', 9]
</code></pre>
<p>i've tried converting all list values to even case during comparison by adding x[0].lower etc. but no use. How do i force python (i'm working on 2.4 version) to do case-insensitive alphabetical sorting?</p>
<p><strong>Edited:</strong></p>
<blockquote>
<p>Jarret and Brian, your
assumptions about parenthesis were
right! I did forget to put them in! And Jarret, your suggestions about not using "cmp" works like a charm! Thanks a lot guys!</p>
</blockquote>
| 1
|
2009-04-02T15:37:15Z
| 710,301
|
<pre><code>ak.sort(cmp=lambda x, y: cmp(x[0].lower(), y[0].lower()))
</code></pre>
<p>Did you forget the parens in <code>x[0].lower()</code>?</p>
| 3
|
2009-04-02T15:42:26Z
|
[
"python"
] |
Python 3.0 Windows/COM
| 710,278
|
<p>How to access a COM object from a python file using python 3.0. </p>
<p>And, yes, I know that not a lot of people are using Python 3.0. Switching back to 2.6 is a <em>huge</em> hassle for me, so I don't want to unless I absolutely have to. </p>
<p>I appreciate your time, and any assistance!</p>
| 1
|
2009-04-02T15:39:19Z
| 710,305
|
<p>Install <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow">pywin32</a> and then create the object using it's progid:</p>
<pre><code>import win32com.client
object = win32com.client.Dispatch("Outlook.Application")
</code></pre>
<p>See also the <a href="http://www.boddie.org.uk/python/COM.html" rel="nofollow">Python and COM tutorial</a>.</p>
<p>EDIT: Hmm... looks like they may not have a python 3.0 version yet. </p>
| 4
|
2009-04-02T15:42:49Z
|
[
"python",
"com",
"python-3.x"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 710,598
|
<p>Both ways are supported for a reason: there are times when one is more appropriate than the other.</p>
<p>import module: nice when you are using many bits from the module. drawback is that you'll need to qualify each reference with the module name.</p>
<p>from module import ...: nice that imported items are usable directly without module name prefix. drawback is that you must list each thing you use, and that it's not clear in code where something came from.</p>
<p>Which to use depends on which makes the code clear and readable, and has more than a little to do with personal preference. I lean toward <code>import module</code> generally because in the code it's very clear where an object or function came from. I use <code>from module import ...</code> when I'm using some object/function a <em>lot</em> in the code.</p>
| 27
|
2009-04-02T16:50:35Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 710,603
|
<p>The difference between <code>import module</code> and <code>from module import foo</code> is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.</p>
<p><code>import module</code></p>
<ul>
<li><strong>Pros:</strong>
<ul>
<li>Less maintenance of your <code>import</code> statements. Don't need to add any additional imports to start using another item from the module</li>
</ul></li>
<li><strong>Cons:</strong>
<ul>
<li>Typing <code>module.foo</code> in your code can be tedious and redundant (tedium can be minimized by using <code>import module as mo</code> then typing <code>mo.foo</code>)</li>
</ul></li>
</ul>
<p><code>from module import foo</code></p>
<ul>
<li><strong>Pros:</strong>
<ul>
<li>Less typing to use <code>foo</code></li>
<li>More control over which items of a module can be accessed</li>
</ul></li>
<li><strong>Cons:</strong>
<ul>
<li>To use a new item from the module you have to update your <code>import</code> statement</li>
<li>You lose context about <code>foo</code>. For example, it's less clear what <code>ceil()</code> does compared to <code>math.ceil()</code></li>
</ul></li>
</ul>
<p>Either method is acceptable, but <strong>don't</strong> use <code>from module import *</code>. </p>
<p>For any reasonable large set of code, if you <code>import *</code> you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the <code>import</code> any more but it's extremely difficult to be sure.</p>
| 181
|
2009-04-02T16:52:11Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 710,606
|
<pre><code>import module
</code></pre>
<p>Is best when you will use many functions from the module.</p>
<pre><code>from module import function
</code></pre>
<p>Is best when you want to avoid polluting the global namespace with all the functions and types from a module when you only need <code>function</code>.</p>
| 9
|
2009-04-02T16:52:49Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 710,656
|
<p>I personally always use </p>
<pre><code>from package.subpackage.subsubpackage import module
</code></pre>
<p>and then access everything as</p>
<pre><code>module.function
module.modulevar
</code></pre>
<p>etc. The reason is that at the same time you have short invocation, and you clearly define the module namespace of each routine, something that is very useful if you have to search for usage of a given module in your source.</p>
<p>Needless to say, do not use the import *, because it pollutes your namespace and it does not tell you where a given function comes from (from which module)</p>
<p>Of course, you can run in trouble if you have the same module name for two different modules in two different packages, like</p>
<pre><code>from package1.subpackage import module
from package2.subpackage import module
</code></pre>
<p>in this case, of course you run into troubles, but then there's a strong hint that your package layout is flawed, and you have to rethink it.</p>
| 24
|
2009-04-02T17:03:54Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 710,831
|
<p>To add to what people have said about <code>from x import *</code>: besides making it more difficult to tell where names came from, this throws off code checkers like Pylint. They will report those names as undefined variables.</p>
| 4
|
2009-04-02T17:46:08Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 710,861
|
<p>My own answer to this depends mostly on first, how many different modules I'll be using. If i'm only going to use one or two, I'll often use <strong><code>from</code></strong> ... <strong><code>import</code></strong> since it makes for fewer keystrokes in the rest of the file, but if I'm going to make use of many different modules, I prefer just <strong><code>import</code></strong> because that means that each module reference is self-documenting. I can see where each symbol comes from without having to hunt around.</p>
<p>Usuaully I prefer the self documenting style of plain import and only change to from.. import when the number of times I have to type the module name grows above 10 to 20, even if there's only one module being imported.</p>
| 2
|
2009-04-02T17:53:14Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 16,688,845
|
<p>I've just discovered one more subtle difference between these two methods.</p>
<p>If module <code>foo</code> uses a following import:</p>
<pre><code>from itertools import count
</code></pre>
<p>Then module <code>bar</code> can by mistake use <code>count</code> as though it was defined in <code>foo</code>, not in <code>itertools</code>:</p>
<pre><code>import foo
foo.count()
</code></pre>
<p>If <code>foo</code> uses:</p>
<pre><code>import itertools
</code></pre>
<p>the mistake is still possible, but less likely to be made. <code>bar</code> needs to:</p>
<pre><code>import foo
foo.itertools.count()
</code></pre>
<p>This caused some troubles to me. I had a module that by mistake imported an exception from a module that did not define it, only imported it from other module (using <code>from module import SomeException</code>). When the import was no longer needed and removed, the offending module was broken.</p>
| 3
|
2013-05-22T09:56:25Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 19,185,936
|
<p>There's another detail here, not mentioned, related to writing to a module. Granted this may not be very common, but I've needed it from time to time.</p>
<p>Due to the way references and name binding works in Python, if you want to update some symbol in a module, say foo.bar, from outside that module, and have other importing code "see" that change, you have to import foo a certain way. For example:</p>
<p>module foo:</p>
<pre><code>bar = "apples"
</code></pre>
<p>module a:</p>
<pre><code>import foo
foo.bar = "oranges" # update bar inside foo module object
</code></pre>
<p>module b:</p>
<pre><code>import foo
print foo.bar # if executed after a's "foo.bar" assignment, will print "oranges"
</code></pre>
<p>However, if you import symbol names instead of module names, this will not work.</p>
<p>For example, if I do this in module a:</p>
<pre><code>from foo import bar
bar = "oranges"
</code></pre>
<p>No code outside of a will see bar as "oranges" because my setting of bar merely affected the name "bar" inside module a, it did not "reach into" the foo module object and update its "bar".</p>
| 11
|
2013-10-04T16:10:12Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 21,170,625
|
<p>Here is another difference not mentioned. This is copied verbatim from <a href="http://docs.python.org/2/tutorial/modules.html" rel="nofollow">http://docs.python.org/2/tutorial/modules.html</a></p>
<p>Note that when using </p>
<pre><code>from package import item
</code></pre>
<p>the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.</p>
<p>Contrarily, when using syntax like </p>
<pre><code>import item.subitem.subsubitem
</code></pre>
<p>each item except for the last must be a package; the last item can be a module or a package but canât be a class or function or variable defined in the previous item.</p>
| 3
|
2014-01-16T19:05:39Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 21,547,583
|
<p>Already many people explained about <code>import</code> vs <code>from</code>, even I want to try to explain a bit more under the hood, where are all the places it got changes:</p>
<p><strong>First of all let me explain:</strong></p>
<p><strong>import X :</strong></p>
<pre><code>imports the module X, and creates a reference to that module in the current
namespace. Then you need to define completed module path to access a
particular attribute or method from inside the module.
</code></pre>
<p>For example: X.name or X.attribute</p>
<p><strong>from X import * :</strong></p>
<pre><code>*imports the module X, and creates references to all public objects
defined by that module in the current namespace (that is, everything
that doesnât have a name starting with â_â) or what ever the name
you mentioned.
Or in other words, after youâve run this statement, you can simply
use a plain name to refer to things defined in module X. But X itself
is not defined, so X.name doesnât work. And if name was already
defined, it is replaced by the new version. And if name in X is
changed to point to some other object, your module wonât notice.
* This makes all names from the module available in the local namespace.
</code></pre>
<p>Now letâs see when we do <code>import X.Y</code>:</p>
<pre><code>>>> import sys
>>> import os.path
</code></pre>
<p>Check sys.modules with name <code>os</code> and <code>os.path</code>:</p>
<pre><code>>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
</code></pre>
<p>Check globals() and locals() namespace dict with name <code>os</code> and <code>os.path</code>:</p>
<pre><code> >>> globals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> locals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> globals()['os.path']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'os.path'
>>>
</code></pre>
<p>From the above example we found that only <code>os</code> is inserted in the local and global namespace.
So, we should be able to use:</p>
<pre><code> >>> os
<module 'os' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> os.path
<module 'posixpath' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>>
</code></pre>
<p>But not <code>path</code></p>
<pre><code>>>> path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>
</code></pre>
<p>Once you delete the <code>os</code> from locals() namespace, you won't be able to access <code>os</code> as well as <code>os.path</code> even though they exist in sys.modules:</p>
<pre><code>>>> del locals()['os']
>>> os
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>> os.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
</code></pre>
<p><strong>Now let's come to <code>from</code> :</strong></p>
<p>** from :**</p>
<pre><code>>>> import sys
>>> from os import path
</code></pre>
<p><strong>Check sys.modules with name os and os.path:</strong></p>
<pre><code>>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
</code></pre>
<p><strong>Oh, we found that in sys.modules we found as same as we did before by using <code>import name</code></strong></p>
<p>OK, let's check how it looks like in <strong>locals() and globals()</strong> namespace dict:</p>
<pre><code>>>> globals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> locals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['os']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'os'
>>>
</code></pre>
<p>You can access by using name <code>path</code> not by <code>os.path</code>:</p>
<pre><code>>>> path
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> os.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
</code></pre>
<p>Let's delete 'path' from locals():</p>
<pre><code>>>> del locals()['path']
>>> path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>
</code></pre>
<p>One final example using an alias:</p>
<pre><code>>>> from os import path as HELL_BOY
>>> locals()['HELL_BOY']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['HELL_BOY']
<module 'posixpath' from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>>
</code></pre>
<p>And no path defined:</p>
<pre><code>>>> globals()['path']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'path'
>>>
</code></pre>
| 11
|
2014-02-04T08:40:54Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 28,654,914
|
<pre><code>import package
import module
</code></pre>
<p>With <code>import</code>, the token must be a package (a file containing Python commands) or a module (a folder in the <code>sys.path</code> containing a file <code>__init__.py</code>.)</p>
<p>When there are subpackages:</p>
<pre><code>import package1.package2.package
import package1.package2.module
</code></pre>
<p>the requirements for folder (package) or file (module) are the same, but the folder or file must be inside <code>package2</code> which must be inside <code>package1</code>, and both <code>package1</code> and <code>package2</code> must contain <code>__init__.py</code> files. <a href="https://docs.python.org/2/tutorial/modules.html" rel="nofollow">https://docs.python.org/2/tutorial/modules.html</a></p>
<p>With the <code>from</code> style of import:</p>
<pre><code>from package1.package2 import package
from package1.package2 import module
</code></pre>
<p>the package or module enters the namespace of the file containing the <code>import</code> statement as <code>module</code> (or <code>package</code>) instead of <code>package1.package2.module</code>. You can always bind to a more convenient name:</p>
<pre><code>a = big_package_name.subpackage.even_longer_subpackage_name.function
</code></pre>
<p>Only the <code>from</code> style of import permits you to name a particular function or variable:</p>
<pre><code>from package3.module import some_function
</code></pre>
<p>is allowed, but</p>
<pre><code>import package3.module.some_function
</code></pre>
<p>is not allowed.</p>
| 1
|
2015-02-22T05:37:51Z
|
[
"python",
"python-import"
] |
'import module' or 'from module import'
| 710,551
|
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.</p>
<p>Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any <em>gotchas</em> down the road.</p>
| 138
|
2009-04-02T16:40:49Z
| 34,892,472
|
<p>Import Module - You don't need additional efforts to fetch another thing from module. It has disadvantages such as redundant typing </p>
<p>Module Import From - Less typing &More control over which items of a module can be accessed.To use a new item from the module you have to update your import statement.</p>
| 0
|
2016-01-20T05:51:40Z
|
[
"python",
"python-import"
] |
Checking a Python module version at runtime
| 710,609
|
<p>Many third-party Python modules have an attribute which holds the version information for the module (usually something like <code>module.VERSION</code> or <code>module.__version__</code>), however some do not.</p>
<p>Particular examples of such modules are libxslt and libxml2.</p>
<p>I need to check that the correct version of these modules are being used at runtime. Is there a way to do this?</p>
<p>A potential solution wold be to read in the source at runtime, hash it, and then compare it to the hash of the known version, but that's nasty. </p>
<p>Is there a better solutions?</p>
| 94
|
2009-04-02T16:53:08Z
| 710,642
|
<p>Some ideas:</p>
<ol>
<li>Try checking for functions that exist or don't exist in your needed versions.</li>
<li>If there are no function differences, inspect function arguments and signatures.</li>
<li>If you can't figure it out from function signatures, set up some stub calls at import time and check their behavior.</li>
</ol>
| 5
|
2009-04-02T16:58:33Z
|
[
"python",
"module",
"version"
] |
Checking a Python module version at runtime
| 710,609
|
<p>Many third-party Python modules have an attribute which holds the version information for the module (usually something like <code>module.VERSION</code> or <code>module.__version__</code>), however some do not.</p>
<p>Particular examples of such modules are libxslt and libxml2.</p>
<p>I need to check that the correct version of these modules are being used at runtime. Is there a way to do this?</p>
<p>A potential solution wold be to read in the source at runtime, hash it, and then compare it to the hash of the known version, but that's nasty. </p>
<p>Is there a better solutions?</p>
| 94
|
2009-04-02T16:53:08Z
| 710,653
|
<p>I'd stay away from hashing. The version of libxslt being used might contain some type of patch that doesn't effect your use of it. </p>
<p>As an alternative, I'd like to suggest that you don't check at run time (don't know if that's a hard requirement or not). For the python stuff I write that has external dependencies (3rd party libraries), I write a script that users can run to check their python install to see if the appropriate versions of modules are installed. </p>
<p>For the modules that don't have a defined 'version' attribute, you can inspect the interfaces it contains (classes and methods) and see if they match the interface they expect. Then in the actual code that you're working on, assume that the 3rd party modules have the interface you expect.</p>
| 5
|
2009-04-02T17:02:16Z
|
[
"python",
"module",
"version"
] |
Checking a Python module version at runtime
| 710,609
|
<p>Many third-party Python modules have an attribute which holds the version information for the module (usually something like <code>module.VERSION</code> or <code>module.__version__</code>), however some do not.</p>
<p>Particular examples of such modules are libxslt and libxml2.</p>
<p>I need to check that the correct version of these modules are being used at runtime. Is there a way to do this?</p>
<p>A potential solution wold be to read in the source at runtime, hash it, and then compare it to the hash of the known version, but that's nasty. </p>
<p>Is there a better solutions?</p>
| 94
|
2009-04-02T16:53:08Z
| 4,939,465
|
<p>Use <a href="https://pythonhosted.org/setuptools/pkg_resources.html">pkg_resources</a>. Anything installed from PyPI at least should have a version number.</p>
<pre><code>>>> import pkg_resources
>>> pkg_resources.get_distribution("blogofile").version
'0.7.1'
</code></pre>
| 203
|
2011-02-08T22:54:17Z
|
[
"python",
"module",
"version"
] |
Checking a Python module version at runtime
| 710,609
|
<p>Many third-party Python modules have an attribute which holds the version information for the module (usually something like <code>module.VERSION</code> or <code>module.__version__</code>), however some do not.</p>
<p>Particular examples of such modules are libxslt and libxml2.</p>
<p>I need to check that the correct version of these modules are being used at runtime. Is there a way to do this?</p>
<p>A potential solution wold be to read in the source at runtime, hash it, and then compare it to the hash of the known version, but that's nasty. </p>
<p>Is there a better solutions?</p>
| 94
|
2009-04-02T16:53:08Z
| 39,652,019
|
<p>You can use </p>
<pre><code>pip freeze
</code></pre>
<p>to see the installed packages in requirements format.</p>
| 0
|
2016-09-23T03:18:03Z
|
[
"python",
"module",
"version"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.