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 |
|---|---|---|---|---|---|---|---|---|---|
How to walk up a linked-list using a list comprehension? | 1,020,037 | <p>I've been trying to think of a way to traverse a hierarchical structure, like a linked list, using a list expression, but haven't come up with anything that seems to work.</p>
<p>Basically, I want to convert this code:</p>
<pre><code>p = self.parent
names = []
while p:
names.append(p.name)
p = p.parent
print ".".join(names)
</code></pre>
<p>into a one-liner like:</p>
<pre><code>print ".".join( [o.name for o in <???>] )
</code></pre>
<p>I'm not sure how to do the traversal in the <code>???</code> part, though, <em>in a generic way</em> (if its even possible). I have several structures with similar <code>.parent</code> type attributes, and don't want to have write a yielding function for each.</p>
<p>Edit:</p>
<p>I can't use the <code>__iter__</code> methods of the object itself because its already used for iterating over the values contained within the object itself. Most other answers, except for liori's, hardcode the attribute name, which is what I want to avoid.</p>
<p>Here's my adaptation based upon liori's answer:</p>
<pre><code>import operator
def walk(attr, start):
if callable(attr):
getter = attr
else:
getter = operator.attrgetter(attr)
o = getter(start)
while o:
yield o
o = getter(o)
</code></pre>
| 1 | 2009-06-19T21:12:29Z | 1,020,059 | <p>The closest thing I can think of is to create a parent generator:</p>
<pre><code># Generate a node's parents, heading towards ancestors
def gen_parents(node):
node = node.parent
while node:
yield node
node = node.parent
# Now you can do this
parents = [x.name for x in gen_parents(node)]
print '.'.join(parents)
</code></pre>
| 6 | 2009-06-19T21:18:08Z | [
"python",
"list-comprehension"
] |
How to walk up a linked-list using a list comprehension? | 1,020,037 | <p>I've been trying to think of a way to traverse a hierarchical structure, like a linked list, using a list expression, but haven't come up with anything that seems to work.</p>
<p>Basically, I want to convert this code:</p>
<pre><code>p = self.parent
names = []
while p:
names.append(p.name)
p = p.parent
print ".".join(names)
</code></pre>
<p>into a one-liner like:</p>
<pre><code>print ".".join( [o.name for o in <???>] )
</code></pre>
<p>I'm not sure how to do the traversal in the <code>???</code> part, though, <em>in a generic way</em> (if its even possible). I have several structures with similar <code>.parent</code> type attributes, and don't want to have write a yielding function for each.</p>
<p>Edit:</p>
<p>I can't use the <code>__iter__</code> methods of the object itself because its already used for iterating over the values contained within the object itself. Most other answers, except for liori's, hardcode the attribute name, which is what I want to avoid.</p>
<p>Here's my adaptation based upon liori's answer:</p>
<pre><code>import operator
def walk(attr, start):
if callable(attr):
getter = attr
else:
getter = operator.attrgetter(attr)
o = getter(start)
while o:
yield o
o = getter(o)
</code></pre>
| 1 | 2009-06-19T21:12:29Z | 1,020,394 | <p>Your LinkedList needs to be iterable for it to work properly. </p>
<p><a href="http://heather.cs.ucdavis.edu/~matloff/Python/PyIterGen.pdf" rel="nofollow">Here's a good resource on it. (PDF warning)</a> It is very in depth on both iterators and generators.</p>
<p>Once you do that, you'll be able to just do this:</p>
<pre><code>print ".".join( [o.name for o in self] )
</code></pre>
| 1 | 2009-06-19T22:57:35Z | [
"python",
"list-comprehension"
] |
How to walk up a linked-list using a list comprehension? | 1,020,037 | <p>I've been trying to think of a way to traverse a hierarchical structure, like a linked list, using a list expression, but haven't come up with anything that seems to work.</p>
<p>Basically, I want to convert this code:</p>
<pre><code>p = self.parent
names = []
while p:
names.append(p.name)
p = p.parent
print ".".join(names)
</code></pre>
<p>into a one-liner like:</p>
<pre><code>print ".".join( [o.name for o in <???>] )
</code></pre>
<p>I'm not sure how to do the traversal in the <code>???</code> part, though, <em>in a generic way</em> (if its even possible). I have several structures with similar <code>.parent</code> type attributes, and don't want to have write a yielding function for each.</p>
<p>Edit:</p>
<p>I can't use the <code>__iter__</code> methods of the object itself because its already used for iterating over the values contained within the object itself. Most other answers, except for liori's, hardcode the attribute name, which is what I want to avoid.</p>
<p>Here's my adaptation based upon liori's answer:</p>
<pre><code>import operator
def walk(attr, start):
if callable(attr):
getter = attr
else:
getter = operator.attrgetter(attr)
o = getter(start)
while o:
yield o
o = getter(o)
</code></pre>
| 1 | 2009-06-19T21:12:29Z | 1,020,488 | <p>If you want your solution to be general, use a general techique. This is a fixed-point like generator:</p>
<pre><code>def fixedpoint(f, start, stop):
while start != stop:
yield start
start = f(start)
</code></pre>
<p>It will return a generator yielding start, f(start), f(f(start)), f(f(f(start))), ..., as long as neither of these values are equal to stop.</p>
<p>Usage:</p>
<pre><code>print ".".join(x.name for x in fixedpoint(lambda p:p.parent, self, None))
</code></pre>
<p>My personal helpers library has similar fixedpoint-like function for years... it is pretty useful for quick hacks.</p>
| 2 | 2009-06-19T23:38:10Z | [
"python",
"list-comprehension"
] |
Writing with Python's built-in .csv module | 1,020,053 | <p>[Please note that this is a different question from the already answered <a href="http://stackoverflow.com/questions/1019200/how-to-replace-a-column-using-pythons-built-in-csv-writer-module">How to replace a column using Pythonâs built-in .csv writer module?</a>]</p>
<p>I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python.</p>
<p>I'm having trouble when I try to write back to a .csv file after making a change to the contents of an entry. I've read the <a href="http://docs.python.org/3.0/library/csv.html">official csv module documentation</a> about how to use the writer, but there isn't an example that covers this case. Specifically, I am trying to get the read, replace, and write operations accomplished in one loop. However, one cannot use the same 'row' reference in both the for loop's argument and as the parameter for writer.writerow(). So, once I've made the change in the for loop, how should I write back to the file?</p>
<p><strong>edit:</strong> I implemented the suggestions from S. Lott and Jimmy, still the same result</p>
<p><strong>edit #2:</strong> I added the "rb" and "wb" to the open() functions, per S. Lott's suggestion</p>
<pre><code>import csv
#filename = 'C:/Documents and Settings/username/My Documents/PALTemplateData.xls'
csvfile = open("PALTemplateData.csv","rb")
csvout = open("PALTemplateDataOUT.csv","wb")
reader = csv.reader(csvfile)
writer = csv.writer(csvout)
changed = 0;
for row in reader:
row[-1] = row[-1].replace('/?', '?')
writer.writerow(row) #this is the line that's causing issues
changed=changed+1
print('Total URLs changed:', changed)
</code></pre>
<p><strong>edit:</strong> For your reference, this is the <strong>new</strong> full traceback from the interpreter:</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\g41092\My Documents\palScript.py", line 13, in <module>
for row in reader:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
</code></pre>
| 7 | 2009-06-19T21:17:07Z | 1,020,074 | <p>the problem is you're trying to write to the same file you're reading from. write to a different file and then rename it after deleting the original.</p>
| 2 | 2009-06-19T21:22:24Z | [
"python",
"file-io",
"csv",
"python-3.x"
] |
Writing with Python's built-in .csv module | 1,020,053 | <p>[Please note that this is a different question from the already answered <a href="http://stackoverflow.com/questions/1019200/how-to-replace-a-column-using-pythons-built-in-csv-writer-module">How to replace a column using Pythonâs built-in .csv writer module?</a>]</p>
<p>I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python.</p>
<p>I'm having trouble when I try to write back to a .csv file after making a change to the contents of an entry. I've read the <a href="http://docs.python.org/3.0/library/csv.html">official csv module documentation</a> about how to use the writer, but there isn't an example that covers this case. Specifically, I am trying to get the read, replace, and write operations accomplished in one loop. However, one cannot use the same 'row' reference in both the for loop's argument and as the parameter for writer.writerow(). So, once I've made the change in the for loop, how should I write back to the file?</p>
<p><strong>edit:</strong> I implemented the suggestions from S. Lott and Jimmy, still the same result</p>
<p><strong>edit #2:</strong> I added the "rb" and "wb" to the open() functions, per S. Lott's suggestion</p>
<pre><code>import csv
#filename = 'C:/Documents and Settings/username/My Documents/PALTemplateData.xls'
csvfile = open("PALTemplateData.csv","rb")
csvout = open("PALTemplateDataOUT.csv","wb")
reader = csv.reader(csvfile)
writer = csv.writer(csvout)
changed = 0;
for row in reader:
row[-1] = row[-1].replace('/?', '?')
writer.writerow(row) #this is the line that's causing issues
changed=changed+1
print('Total URLs changed:', changed)
</code></pre>
<p><strong>edit:</strong> For your reference, this is the <strong>new</strong> full traceback from the interpreter:</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\g41092\My Documents\palScript.py", line 13, in <module>
for row in reader:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
</code></pre>
| 7 | 2009-06-19T21:17:07Z | 1,020,077 | <p>You cannot read and write the same file.</p>
<pre><code>source = open("PALTemplateData.csv","rb")
reader = csv.reader(source , dialect)
target = open("AnotherFile.csv","wb")
writer = csv.writer(target , dialect)
</code></pre>
<p>The normal approach to ALL file manipulation is to create a modified COPY of the original file. Don't try to update files in place. It's just a bad plan.</p>
<hr>
<p><strong>Edit</strong></p>
<p>In the lines</p>
<pre><code>source = open("PALTemplateData.csv","rb")
target = open("AnotherFile.csv","wb")
</code></pre>
<p>The "rb" and "wb" are absolutely required. Every time you ignore those, you open the file for reading in the wrong format.</p>
<p>You must use "rb" to read a .CSV file. There is no choice with Python 2.x. With Python 3.x, you can omit this, but use "r" explicitly to make it clear.</p>
<p>You must use "wb" to write a .CSV file. There is no choice with Python 2.x. With Python 3.x, you must use "w". </p>
<hr>
<p><strong>Edit</strong></p>
<p>It appears you are using Python3. You'll need to drop the "b" from "rb" and "wb".</p>
<p>Read this: <a href="http://docs.python.org/3.0/library/functions.html#open" rel="nofollow">http://docs.python.org/3.0/library/functions.html#open</a></p>
| 10 | 2009-06-19T21:23:05Z | [
"python",
"file-io",
"csv",
"python-3.x"
] |
Writing with Python's built-in .csv module | 1,020,053 | <p>[Please note that this is a different question from the already answered <a href="http://stackoverflow.com/questions/1019200/how-to-replace-a-column-using-pythons-built-in-csv-writer-module">How to replace a column using Pythonâs built-in .csv writer module?</a>]</p>
<p>I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python.</p>
<p>I'm having trouble when I try to write back to a .csv file after making a change to the contents of an entry. I've read the <a href="http://docs.python.org/3.0/library/csv.html">official csv module documentation</a> about how to use the writer, but there isn't an example that covers this case. Specifically, I am trying to get the read, replace, and write operations accomplished in one loop. However, one cannot use the same 'row' reference in both the for loop's argument and as the parameter for writer.writerow(). So, once I've made the change in the for loop, how should I write back to the file?</p>
<p><strong>edit:</strong> I implemented the suggestions from S. Lott and Jimmy, still the same result</p>
<p><strong>edit #2:</strong> I added the "rb" and "wb" to the open() functions, per S. Lott's suggestion</p>
<pre><code>import csv
#filename = 'C:/Documents and Settings/username/My Documents/PALTemplateData.xls'
csvfile = open("PALTemplateData.csv","rb")
csvout = open("PALTemplateDataOUT.csv","wb")
reader = csv.reader(csvfile)
writer = csv.writer(csvout)
changed = 0;
for row in reader:
row[-1] = row[-1].replace('/?', '?')
writer.writerow(row) #this is the line that's causing issues
changed=changed+1
print('Total URLs changed:', changed)
</code></pre>
<p><strong>edit:</strong> For your reference, this is the <strong>new</strong> full traceback from the interpreter:</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\g41092\My Documents\palScript.py", line 13, in <module>
for row in reader:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
</code></pre>
| 7 | 2009-06-19T21:17:07Z | 1,027,955 | <p>Opening csv files as binary is just wrong. CSV are normal text files so You need to open them with</p>
<pre><code>source = open("PALTemplateData.csv","r")
target = open("AnotherFile.csv","w")
</code></pre>
<p>The error </p>
<pre><code>_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
</code></pre>
<p>comes because You are opening them in binary mode.</p>
<p>When I was opening excel csv's with python, I used something like:</p>
<pre><code>try: # checking if file exists
f = csv.reader(open(filepath, "r", encoding="cp1250"), delimiter=";", quotechar='"')
except IOError:
f = []
for record in f:
# do something with record
</code></pre>
<p>and it worked rather fast (I was opening two about 10MB each csv files, though I did this with python 2.6, not the 3.0 version).</p>
<p>There are few working modules for working with excel csv files from within python - <a href="http://sourceforge.net/projects/pyexcelerator" rel="nofollow">pyExcelerator</a> is one of them.</p>
| 3 | 2009-06-22T15:51:08Z | [
"python",
"file-io",
"csv",
"python-3.x"
] |
Self Referencing Class Definition in python | 1,020,279 | <p>is there any way to reference a class name from within the class declaration? an example follows:</p>
<pre><code>class Plan(SiloBase):
cost = DataField(int)
start = DataField(System.DateTime)
name = DataField(str)
items = DataCollection(int)
subPlan = ReferenceField(Plan)
</code></pre>
<p>i've got a metaclass that reads this information and does some setup, and the base class implements some common saving stuff. i would love to be able to create recursive definitions like this, but so far in my experimentation i have been unable to get the effect i desire, usually running into a "Plan is not defined" error. I understand what is happening, the name of the class isn't in scope inside the class.</p>
| 19 | 2009-06-19T22:14:40Z | 1,020,291 | <p><strong>Try this:</strong></p>
<pre><code>class Plan(SiloBase):
cost = DataField(int)
start = DataField(System.DateTime)
name = DataField(str)
items = DataCollection(int)
Plan.subPlan = ReferenceField(Plan)
</code></pre>
<p><strong>OR use <code>__new__</code> like this:</strong></p>
<pre><code>class Plan(SiloBase):
def __new__(cls, *args, **kwargs):
cls.cost = DataField(int)
cls.start = DataField(System.DateTime)
cls.name = DataField(str)
cls.items = DataCollection(int)
cls.subPlan = ReferenceField(cls)
return object.__new__(cls, *args, **kwargs)
</code></pre>
| 21 | 2009-06-19T22:18:31Z | [
"python"
] |
Self Referencing Class Definition in python | 1,020,279 | <p>is there any way to reference a class name from within the class declaration? an example follows:</p>
<pre><code>class Plan(SiloBase):
cost = DataField(int)
start = DataField(System.DateTime)
name = DataField(str)
items = DataCollection(int)
subPlan = ReferenceField(Plan)
</code></pre>
<p>i've got a metaclass that reads this information and does some setup, and the base class implements some common saving stuff. i would love to be able to create recursive definitions like this, but so far in my experimentation i have been unable to get the effect i desire, usually running into a "Plan is not defined" error. I understand what is happening, the name of the class isn't in scope inside the class.</p>
| 19 | 2009-06-19T22:14:40Z | 1,020,296 | <p>No, you can't do that. Think about what would happen if you did this:</p>
<pre><code> OtherPlan = Plan
other_plan = OtherPlan()
</code></pre>
<p>At instantiation of <code>other_plan</code>, what is the name of the class?</p>
<p>Anyway, this sort of thing is best done in the <code>__new__</code> method, which takes a <code>cls</code> parameter referring to the class.</p>
| 0 | 2009-06-19T22:20:47Z | [
"python"
] |
Self Referencing Class Definition in python | 1,020,279 | <p>is there any way to reference a class name from within the class declaration? an example follows:</p>
<pre><code>class Plan(SiloBase):
cost = DataField(int)
start = DataField(System.DateTime)
name = DataField(str)
items = DataCollection(int)
subPlan = ReferenceField(Plan)
</code></pre>
<p>i've got a metaclass that reads this information and does some setup, and the base class implements some common saving stuff. i would love to be able to create recursive definitions like this, but so far in my experimentation i have been unable to get the effect i desire, usually running into a "Plan is not defined" error. I understand what is happening, the name of the class isn't in scope inside the class.</p>
| 19 | 2009-06-19T22:14:40Z | 1,020,302 | <blockquote>
<p>I understand what is happening, the
name of the class isn't in scope
inside the class.</p>
</blockquote>
<p>Not exactly. The name of the class <strong>is not yet defined</strong> when defining it's contents (e.g. scope).</p>
| 1 | 2009-06-19T22:23:54Z | [
"python"
] |
Self Referencing Class Definition in python | 1,020,279 | <p>is there any way to reference a class name from within the class declaration? an example follows:</p>
<pre><code>class Plan(SiloBase):
cost = DataField(int)
start = DataField(System.DateTime)
name = DataField(str)
items = DataCollection(int)
subPlan = ReferenceField(Plan)
</code></pre>
<p>i've got a metaclass that reads this information and does some setup, and the base class implements some common saving stuff. i would love to be able to create recursive definitions like this, but so far in my experimentation i have been unable to get the effect i desire, usually running into a "Plan is not defined" error. I understand what is happening, the name of the class isn't in scope inside the class.</p>
| 19 | 2009-06-19T22:14:40Z | 1,020,431 | <blockquote>
<p>i've got a metaclass that reads this information and does some setup</p>
</blockquote>
<p>Most frameworks that use metaclasses provide a way to resolve this. For instance, <a href="http://docs.djangoproject.com/en/1.0/ref/models/fields/#foreignkey">Django</a>:</p>
<pre><code>subplan = ForeignKey('self')
</code></pre>
<p><a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#SelfReferenceProperty">Google App Engine</a>:</p>
<pre><code>subplan = SelfReferenceProperty()
</code></pre>
<p>The problem with solutions like tacking an additional property on later or using <code>__new__</code> is that most ORM metaclasses expect the class properties to exist at the time when the class is created.</p>
| 8 | 2009-06-19T23:15:00Z | [
"python"
] |
How to do PGP in Python (generate keys, encrypt/decrypt) | 1,020,320 | <p>I'm making a program in Python to be distributed to windows users via an installer.</p>
<p>The program needs to be able to download a file every day encrypted with the user's public key and then decrypt it.</p>
<p>So I need to find a Python library that will let me generate public and private PGP keys, and also decrypt files encrypted with the public key.</p>
<p>Is this something pyCrypto will do (documentation is nebulous)? Are there other pure Python libraries? How about a standalone command line tool in any language?</p>
<p>All I saw so far was GNUPG but installing that on Windows does stuff to the registry and throws dll's everywhere, and then I have to worry about whether the user already has this installed, how to backup their existing keyrings, etc. I'd rather just have a python library or command line tool and mange the keys myself.</p>
<p>Update: pyME might work but it doesn't seem to be compatible with Python 2.4 which I have to use.</p>
| 20 | 2009-06-19T22:28:46Z | 1,020,334 | <p>Some simple web searching turned up these results:</p>
<ul>
<li><a href="http://pyme.sourceforge.net/" rel="nofollow">Pyme</a></li>
<li><a href="http://sourceforge.net/projects/pypgp/" rel="nofollow">Pypgp</a></li>
</ul>
| 1 | 2009-06-19T22:33:53Z | [
"python",
"encryption",
"pgp",
"gnupg"
] |
How to do PGP in Python (generate keys, encrypt/decrypt) | 1,020,320 | <p>I'm making a program in Python to be distributed to windows users via an installer.</p>
<p>The program needs to be able to download a file every day encrypted with the user's public key and then decrypt it.</p>
<p>So I need to find a Python library that will let me generate public and private PGP keys, and also decrypt files encrypted with the public key.</p>
<p>Is this something pyCrypto will do (documentation is nebulous)? Are there other pure Python libraries? How about a standalone command line tool in any language?</p>
<p>All I saw so far was GNUPG but installing that on Windows does stuff to the registry and throws dll's everywhere, and then I have to worry about whether the user already has this installed, how to backup their existing keyrings, etc. I'd rather just have a python library or command line tool and mange the keys myself.</p>
<p>Update: pyME might work but it doesn't seem to be compatible with Python 2.4 which I have to use.</p>
| 20 | 2009-06-19T22:28:46Z | 1,037,087 | <p>PyCrypto supports PGP - albeit you should test it to make sure that it works to your specifications.</p>
<p>Although documentation is hard to come by, if you look through Util/test.py (the module test script), you can find a rudimentary example of their PGP support:</p>
<pre><code>if verbose: print ' PGP mode:',
obj1=ciph.new(password, ciph.MODE_PGP, IV)
obj2=ciph.new(password, ciph.MODE_PGP, IV)
start=time.time()
ciphertext=obj1.encrypt(str)
plaintext=obj2.decrypt(ciphertext)
end=time.time()
if (plaintext!=str):
die('Error in resulting plaintext from PGP mode')
print_timing(256, end-start, verbose)
del obj1, obj2
</code></pre>
<p>Futhermore, PublicKey/pubkey.py provides for the following relevant methods:</p>
<pre><code>def encrypt(self, plaintext, K)
def decrypt(self, ciphertext):
def sign(self, M, K):
def verify (self, M, signature):
def can_sign (self):
"""can_sign() : bool
Return a Boolean value recording whether this algorithm can
generate signatures. (This does not imply that this
particular key object has the private information required to
to generate a signature.)
"""
return 1
</code></pre>
| 6 | 2009-06-24T08:30:10Z | [
"python",
"encryption",
"pgp",
"gnupg"
] |
How to do PGP in Python (generate keys, encrypt/decrypt) | 1,020,320 | <p>I'm making a program in Python to be distributed to windows users via an installer.</p>
<p>The program needs to be able to download a file every day encrypted with the user's public key and then decrypt it.</p>
<p>So I need to find a Python library that will let me generate public and private PGP keys, and also decrypt files encrypted with the public key.</p>
<p>Is this something pyCrypto will do (documentation is nebulous)? Are there other pure Python libraries? How about a standalone command line tool in any language?</p>
<p>All I saw so far was GNUPG but installing that on Windows does stuff to the registry and throws dll's everywhere, and then I have to worry about whether the user already has this installed, how to backup their existing keyrings, etc. I'd rather just have a python library or command line tool and mange the keys myself.</p>
<p>Update: pyME might work but it doesn't seem to be compatible with Python 2.4 which I have to use.</p>
| 20 | 2009-06-19T22:28:46Z | 1,039,320 | <p><a href="http://pyme.sourceforge.net/" rel="nofollow">PyMe</a> does claim full compatibility with Python 2.4, and I quote:</p>
<blockquote>
<p>The latest version of PyMe (as of this
writing) is v0.8.0. Its binary
distribution for Debian was compiled
with SWIG v1.3.33 and GCC v4.2.3 for
GPGME v1.1.6 and Python v2.3.5,
v2.4.4, and v2.5.2 (provided in
'unstable' distribution at the time).
Its binary distribution for Windows
was compiled with SWIG v1.3.29 and
MinGW v4.1 for GPGME v1.1.6 and Python
v2.5.2 (although the same binary get
installed and works fine in v2.4.2 as
well).</p>
</blockquote>
<p>I'm not sure why you say "it doesn't seem to be compatible with Python 2.4 which I have to use" -- specifics please?</p>
<p>And yes it does exist as a semi-Pythonic (SWIGd) wrapper on GPGME -- that's a popular way to develop Python extensions once you have a C library that basically does the job.</p>
<p><a href="http://softlayer.dl.sourceforge.net/sourceforge/pypgp/pgp.py" rel="nofollow">PyPgp</a> has a much simpler approach -- that's why it's a single, simple Python script: basically it does nothing more than "shell out" to command-line PGP commands. For example, decryption is just:</p>
<pre><code>def decrypt(data):
"Decrypt a string - if you have the right key."
pw,pr = os.popen2('pgpv -f')
pw.write(data)
pw.close()
ptext = pr.read()
return ptext
</code></pre>
<p>i.e., write the encrypted cyphertext to the standard input of <code>pgpv -f</code>, read pgpv's standard output as the decrypted plaintext.</p>
<p>PyPgp is also a very old project, though its simplicity means that making it work with modern Python (e.g., subprocess instead of now-deprecated os.popen2) would not be hard. But you still do need <a href="http://www.pgp.com/" rel="nofollow">PGP</a> installed, or PyPgp won't do anything;-).</p>
| 2 | 2009-06-24T16:03:44Z | [
"python",
"encryption",
"pgp",
"gnupg"
] |
How to do PGP in Python (generate keys, encrypt/decrypt) | 1,020,320 | <p>I'm making a program in Python to be distributed to windows users via an installer.</p>
<p>The program needs to be able to download a file every day encrypted with the user's public key and then decrypt it.</p>
<p>So I need to find a Python library that will let me generate public and private PGP keys, and also decrypt files encrypted with the public key.</p>
<p>Is this something pyCrypto will do (documentation is nebulous)? Are there other pure Python libraries? How about a standalone command line tool in any language?</p>
<p>All I saw so far was GNUPG but installing that on Windows does stuff to the registry and throws dll's everywhere, and then I have to worry about whether the user already has this installed, how to backup their existing keyrings, etc. I'd rather just have a python library or command line tool and mange the keys myself.</p>
<p>Update: pyME might work but it doesn't seem to be compatible with Python 2.4 which I have to use.</p>
| 20 | 2009-06-19T22:28:46Z | 1,042,139 | <p><a href="http://chandlerproject.org/Projects/MeTooCrypto" rel="nofollow">M2Crypto</a> has PGP module, but I have actually never tried to use it. If you try it, and it works, please let me know (I am the current M2Crypto maintainer). Some links:</p>
<ul>
<li><a href="http://svn.osafoundation.org/m2crypto/trunk/M2Crypto/PGP/" rel="nofollow">Module sources</a></li>
<li><a href="http://svn.osafoundation.org/m2crypto/trunk/demo/pgp/pgpstep.py" rel="nofollow">Demo Script</a></li>
<li><a href="http://svn.osafoundation.org/m2crypto/trunk/tests/test%5Fpgp.py" rel="nofollow">unit tests</a></li>
</ul>
<p><strong>Update:</strong> The PGP module does not provide ways to generate keys, but presumably these could be created with the lower level <a href="http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.RSA-module.html" rel="nofollow">RSA</a>, <a href="http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.DSA-module.html" rel="nofollow">DSA</a> etc. modules. I don't know PGP insides, so you'd have to dig up the details. Also, if you know how to generate these using openssl command line commands, it should be reasonably easy to convert that to M2Crypto calls.</p>
| 3 | 2009-06-25T04:10:59Z | [
"python",
"encryption",
"pgp",
"gnupg"
] |
How to do PGP in Python (generate keys, encrypt/decrypt) | 1,020,320 | <p>I'm making a program in Python to be distributed to windows users via an installer.</p>
<p>The program needs to be able to download a file every day encrypted with the user's public key and then decrypt it.</p>
<p>So I need to find a Python library that will let me generate public and private PGP keys, and also decrypt files encrypted with the public key.</p>
<p>Is this something pyCrypto will do (documentation is nebulous)? Are there other pure Python libraries? How about a standalone command line tool in any language?</p>
<p>All I saw so far was GNUPG but installing that on Windows does stuff to the registry and throws dll's everywhere, and then I have to worry about whether the user already has this installed, how to backup their existing keyrings, etc. I'd rather just have a python library or command line tool and mange the keys myself.</p>
<p>Update: pyME might work but it doesn't seem to be compatible with Python 2.4 which I have to use.</p>
| 20 | 2009-06-19T22:28:46Z | 1,053,752 | <p>You don't need <code>PyCrypto</code> or <code>PyMe</code>, fine though those packages may be - you will have all kinds of problems building under Windows. Instead, why not avoid the rabbit-holes and do what I did? Use <code>gnupg 1.4.9</code>. You don't need to do a full installation on end-user machines - just <code>gpg.exe</code> and <code>iconv.dll</code> from the distribution are sufficient, and you just need to have them somewhere in the path or accessed from your Python code using a full pathname. No changes to the registry are needed, and everything (executables and data files) can be confined to a single folder if you want.</p>
<p>There's a module <code>GPG.py</code> which was originally written by Andrew Kuchling, improved by Richard Jones and improved further by Steve Traugott. It's available <a href="http://trac.t7a.org/isconf/file/trunk/lib/python/isconf/GPG.py">here</a>, but as-is it's not suitable for Windows because it uses <code>os.fork()</code>. Although originally part of <code>PyCrypto</code>, <strong>it is completely independent of the other parts of <code>PyCrypto</code> and needs only gpg.exe/iconv.dll in order to work</strong>.</p>
<p>I have a version (<code>gnupg.py</code>) derived from Traugott's <code>GPG.py</code>, which uses the <code>subprocess</code> module. It works fine under Windows, at least for my purposes - I use it to do the following:</p>
<ul>
<li>Key management - generation, listing, export etc.</li>
<li>Import keys from an external source (e.g. public keys received from a partner company)</li>
<li>Encrypt and decrypt data</li>
<li>Sign and verify signatures</li>
</ul>
<p>The module I've got is not ideal to show right now, because it includes some other stuff which shouldn't be there - which means I can't release it as-is at the moment. At some point, perhaps in the next couple of weeks, I hope to be able to tidy it up, add some more unit tests (I don't have any unit tests for sign/verify, for example) and release it (either under the original <code>PyCrypto</code> licence or a similar commercial-friendly license). If you can't wait, go with Traugott's module and modify it yourself - it wasn't too much work to make it work with the <code>subprocess</code> module.</p>
<p>This approach was a lot less painful than the others (e.g. <code>SWIG</code>-based solutions, or solutions which require building with <code>MinGW</code>/<code>MSYS</code>), which I considered and experimented with. I've used the same (<code>gpg.exe</code>/<code>iconv.dll</code>) approach with systems written in other languages, e.g. <code>C#</code>, with equally painless results.</p>
<p>P.S. It works with Python 2.4 as well as Python 2.5 and later. Not tested with other versions, though I don't foresee any problems.</p>
| 22 | 2009-06-27T22:12:35Z | [
"python",
"encryption",
"pgp",
"gnupg"
] |
How to do PGP in Python (generate keys, encrypt/decrypt) | 1,020,320 | <p>I'm making a program in Python to be distributed to windows users via an installer.</p>
<p>The program needs to be able to download a file every day encrypted with the user's public key and then decrypt it.</p>
<p>So I need to find a Python library that will let me generate public and private PGP keys, and also decrypt files encrypted with the public key.</p>
<p>Is this something pyCrypto will do (documentation is nebulous)? Are there other pure Python libraries? How about a standalone command line tool in any language?</p>
<p>All I saw so far was GNUPG but installing that on Windows does stuff to the registry and throws dll's everywhere, and then I have to worry about whether the user already has this installed, how to backup their existing keyrings, etc. I'd rather just have a python library or command line tool and mange the keys myself.</p>
<p>Update: pyME might work but it doesn't seem to be compatible with Python 2.4 which I have to use.</p>
| 20 | 2009-06-19T22:28:46Z | 1,214,097 | <p>As other have noted, PyMe is the canonical solution for this, since it's based on GpgME, which is part of the GnuPG ecosystem.</p>
<p>For Windows, I strongly recommend to use <a href="http://www.gpg4win.org" rel="nofollow">Gpg4win</a> as the GnuPG distribution, for two reasons:</p>
<p>It's based on GnuPG 2, which, among other things, includes <code>gpg2.exe</code>, which can (finally, I might add :) start <code>gpg-agent.exe</code> on-demand (gpg v1.x can't).</p>
<p>And secondly, it's the only official Windows build by the GnuPG developers. E.g. it's entirely cross-compiled from Linux to Windows, so not a iota of non-free software was used in preparing it (quite important for a security suite :).</p>
| 2 | 2009-07-31T18:26:43Z | [
"python",
"encryption",
"pgp",
"gnupg"
] |
bug in "django-admin.py makemessages" or xgettext call? -> "warning: unterminated string" | 1,020,432 | <p><strong>django-admin.py makemessages</strong> dies with errors "warning: unterminated string" on cases where really long strings are wrapped:</p>
<pre><code>string = "some text \
more text\
and even more"
</code></pre>
<p>These strings don't even need to be translated - e.g. sql query strings.
The problem goes away when I concatenate the string, but the result looks ugly and it takes time to join them...</p>
<p>Does anyone have a problem like this? Have you found a way to fix it?</p>
<p>I have the following versions of the tools involved:</p>
<p>xgettext-0.17, gettext-0.17, django-1.0.2, python-2.6.2</p>
<p>There was a <a href="http://byteflow.su/ticket/107" rel="nofollow">ticket</a> on this issue, but it was closed probably because the error appears only in some combination of component versions.</p>
<p><strong>EDIT: found the source of problem</strong> - xgettext prints warning messages to sterr and django takes them as fatal errors and quits.</p>
<p>return status of xgettext call is 0 - "success". I guess that django should recognize it as success and not quit because of warnings.</p>
<p>Interestinly xgettext still extracts backslash-wrapped strings if they need to be translated, but gives warnings in stderr (<em>"unterminated string"</em>) and .po file (<em>"internationalized messages should not contain the `\r' escape sequence"</em>)</p>
<p>xgettext call is the following: </p>
<pre><code>xgettext -d django -L Python --keyword=gettext_noop \
--keyword=gettext_lazy --keyword=ngettext_lazy:1,2 \
--keyword=ugettext_noop --keyword=ugettext_lazy \
--keyword=ungettext_lazy:1,2
--from-code UTF-8 -o - source_file.py
</code></pre>
<p>called from django/core/management/commands/makemessages.py</p>
| 0 | 2009-06-19T23:16:04Z | 1,021,293 | <p>I can think of two possibilities: you might have an extra space after your backslash at the end of the line; or you might be somehow ending up with the wrong line-ending characters in your source (e.g. Windows-style when your Python is expecting Unix-style, thus disabling the backslashes).</p>
<p>Either way, I would take advantage of C-style automatic string concatenation:</p>
<pre><code>>>> string = ("some text "
... "more text "
... "and even more")
>>> string
'some text more text and even more'
</code></pre>
<p>Alternatively, if you don't mind newlines ending up in there, use multi-line strings:</p>
<pre><code>>>> string = """some text
... more text
... and even more"""
</code></pre>
<p>IMO these look much nicer, and are much less fragile when refactoring.</p>
<p>Does this help?</p>
| 2 | 2009-06-20T09:20:43Z | [
"python",
"django",
"internationalization",
"xgettext"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 1,020,479 | <p>I think the point of inheritance in Python is not to make the code compile, it is for the real reason of inheritance which is extending the class into another child class, and to override the logic in the base class. However the duck typing in Python makes the "interface" concept useless, because you can just check if the method exist before invokation with no need to use an interface to limit the class structure.</p>
| 8 | 2009-06-19T23:34:45Z | [
"python",
"oop",
"inheritance"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 1,020,482 | <p>You are referring to the run-time duck-typing as "overriding" inheritance, however I believe inheritance has its own merits as a design and implementation approach, being an integral part of object oriented design. In my humble opinion, the question of whether you can achieve something otherwise is not very relevant, because actually you could code Python without classes, functions and more, but the question is how well-designed, robust and readable your code will be.</p>
<p>I can give two examples for where inheritance is the right approach in my opinion, I'm sure there are more. </p>
<p>First, if you code wisely, your makeSpeak function may want to validate that its input is indeed an Animal, and not only that "it can speak", in which case the most elegant method would be to use inheritance. Again, you can do it in other ways, but that's the beauty of object oriented design with inheritance - your code will "really" check whether the input is an "animal".</p>
<p>Second, and clearly more straightforward, is Encapsulation - another integral part of object oriented design. This becomes relevant when the ancestor has data members and/or non-abstract methods. Take the following silly example, in which the ancestor has a function (speak_twice) that invokes a then-abstract function:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
def speak_twice(self):
self.speak()
self.speak()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
</code></pre>
<p>Assuming <code>"speak_twice"</code> is an important feature, you don't want to code it in both Dog and Cat, and I'm sure you can extrapolate this example. Sure, you could implement a Python stand-alone function that will accept some duck-typed object, check whether it has a speak function and invoke it twice, but that's both non-elegant and misses point number 1 (validate it's an Animal). Even worse, and to strengthen the Encapsulation example, what if a member function in the descendant class wanted to use <code>"speak_twice"</code>?</p>
<p>It gets even clearer if the ancestor class has a data member, for example <code>"number_of_legs"</code> that is used by non-abstract methods in the ancestor like <code>"print_number_of_legs"</code>, but is initiated in the descendant class' constructor (e.g. Dog would initialize it with 4 whereas Snake would initialize it with 0). </p>
<p>Again, I'm sure there are endless more examples, but basically every (large enough) software that is based on solid object oriented design will require inheritance.</p>
| 76 | 2009-06-19T23:35:48Z | [
"python",
"oop",
"inheritance"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 1,020,528 | <p>Classes in Python are basically just ways of grouping a bunch of functions and data.. They are different to classes in C++ and such..</p>
<p>I've mostly seen inheritance used for overriding methods of the super-class. For example, perhaps a more Python'ish use of inheritance would be..</p>
<pre><code>from world.animals import Dog
class Cat(Dog):
def speak(self):
print "meow"
</code></pre>
<p>Of course cats aren't a type of dog, but I have this (third party) <code>Dog</code> class which works perfectly, <em>except</em> the <code>speak</code> method which I want to override - this saves re-implementing the entire class, just so it meows. Again, while <code>Cat</code> isn't a type of <code>Dog</code>, but a cat does inherit a lot of attributes..</p>
<p>A much better (practical) example of overriding a method or attribute is how you change the user-agent for urllib. You basically subclass <code>urllib.FancyURLopener</code> and change the version attribute (<a href="http://docs.python.org/library/urllib.html#urllib.%5Furlopener" rel="nofollow">from the documentation</a>):</p>
<pre><code>import urllib
class AppURLopener(urllib.FancyURLopener):
version = "App/1.7"
urllib._urlopener = AppURLopener()
</code></pre>
<p>Another manner exceptions are used is for Exceptions, when inheritance is used in a more "proper" way:</p>
<pre><code>class AnimalError(Exception):
pass
class AnimalBrokenLegError(AnimalError):
pass
class AnimalSickError(AnimalError):
pass
</code></pre>
<p>..you can then catch <code>AnimalError</code> to catch all exceptions which inherit from it, or a specific one like <code>AnimalBrokenLegError</code></p>
| 0 | 2009-06-19T23:52:43Z | [
"python",
"oop",
"inheritance"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 1,020,676 | <p>In C++/Java/etc, polymorphism is caused by inheritance. Abandon that misbegotten belief, and dynamic languages open up to you.</p>
<p>Essentially, in Python there is no interface so much as "the understanding that certain methods are callable". Pretty hand-wavy and academic-sounding, no? It means that because you call "speak" you clearly expect that the object should have a "speak" method. Simple, huh? This is very Liskov-ian in that the users of a class define its interface, a good design concept that leads you into healthier TDD.</p>
<p>So what is left is, as another poster politely managed to avoid saying, a code sharing trick. You could write the same behavior into each "child" class, but that would be redundant. Easier to inherit or mix-in functionality that is invariant across the inheritance hierarchy. Smaller, DRY-er code is better in general. </p>
| 5 | 2009-06-20T01:01:40Z | [
"python",
"oop",
"inheritance"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 1,020,871 | <p>I think that it is very difficult to give a meaningful, concrete answer with such abstract examples...</p>
<p>To simplify, there are two types of inheritance: interface and implementation. If you need to inherit the implementation, then python is not so different than statically typed OO languages like C++. </p>
<p>Inheritance of interface is where there is a big difference, with fundamental consequences for the design of your software in my experience. Languages like Python does not force you to use inheritance in that case, and avoiding inheritance is a good point in most cases, because it is very hard to fix a wrong design choice there later. That's a well known point raised in any good OOP book.</p>
<p>There are cases where using inheritance for interfaces is advisable in Python, for example for plug-ins, etc... For those cases, Python 2.5 and below lacks a "built-in" elegant approach, and several big frameworks designed their own solutions (zope, trac, twister). Python 2.6 and above has <a href="http://www.python.org/dev/peps/pep-3119/#abcs-vs-duck-typing" rel="nofollow">ABC classes to solve this</a>.</p>
| 6 | 2009-06-20T03:31:25Z | [
"python",
"oop",
"inheritance"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 1,020,889 | <p>Inheritance in Python is more of a convenience than anything else. I find that it's best used to provide a class with "default behavior."</p>
<p>Indeed, there is a significant community of Python devs who argue against using inheritance at all. Whatever you do, don't just don't overdo it. Having an overly complicated class hierarchy is a sure way to get labeled a "Java programmer", and you just can't have that. :-)</p>
| 8 | 2009-06-20T03:44:11Z | [
"python",
"oop",
"inheritance"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 1,020,966 | <p>Inheritance in Python is all about code reuse. Factorize common functionality into a base class, and implement different functionality in the derived classes.</p>
| 10 | 2009-06-20T04:51:10Z | [
"python",
"oop",
"inheritance"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 1,041,511 | <p>You can get around inheritance in Python and pretty much any other language. It's all about code reuse and code simplification though. </p>
<p>Just a semantic trick, but after building your classes and base classes, you don't even have to know what's possible with your object to see if you can do it. </p>
<p>Say you have d which is a Dog that subclassed Animal.</p>
<pre><code>command = raw_input("What do you want the dog to do?")
if command in dir(d): getattr(d,command)()
</code></pre>
<p>If whatever the user typed in is available, the code will run the proper method. </p>
<p>Using this you can create whatever combination of Mammal/Reptile/Bird hybrid monstrosity you want, and now you can make it say 'Bark!' while flying and sticking out its forked tongue and it will handle it properly! Have fun with it!</p>
| 1 | 2009-06-24T23:40:17Z | [
"python",
"oop",
"inheritance"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 1,071,345 | <p>I don't see much point in inheritance.</p>
<p>Every time I have ever used inheritance in real systems, I got burned because it led to a tangled web of dependencies, or I simply realised in time that I would be a lot better off without it. Now, I avoid it as much as possible. I simply never have a use for it.</p>
<pre><code>class Repeat:
"Send a message more than once"
def __init__(repeat, times, do):
repeat.times = times
repeat.do = do
def __call__(repeat):
for i in xrange(repeat.times):
repeat.do()
class Speak:
def __init__(speak, animal):
"""
Check that the animal can speak.
If not we can do something about it (e.g. ignore it).
"""
speak.__call__ = animal.speak
def twice(speak):
Repeat(2, speak)()
class Dog:
def speak(dog):
print "Woof"
class Cat:
def speak(cat):
print "Meow"
>>> felix = Cat()
>>> Speak(felix)()
Meow
>>> fido = Dog()
>>> speak = Speak(fido)
>>> speak()
Woof
>>> speak.twice()
Woof
>>> speak_twice = Repeat(2, Speak(felix))
>>> speak_twice()
Meow
Meow
</code></pre>
<p>James Gosling was once asked at a press conference a question along the lines: "If you could go back and do Java differently, what would you leave out?". His response was "Classes", to which there was laughter. However, he was serious and explained that really, it was not classes that were the problem but inheritance.</p>
<p>I kind of view it like a drug dependency - it gives you a quick fix that feels good, but in the end, it messes you up. By that I mean that it is a convenient way to reuse code, but it forces an unhealthy coupling between child and parent class. Changes to the parent may break the child. The child is dependant on the parent for certain functionality and cannot alter that functionality. Therefore the functionality provided by the child is also tied to the parent - you can only have both.</p>
<p>Better is to provide one single client facing class for an interface which implements the interface, using the functionality of other objects which are composed at construction time. Doing this via properly designed interfaces, all coupling can be eliminated and we provide a highly composable API (This is nothing new - most programmers already do this, just not enough). Note that the implementing class must not simply expose functionality, otherwise the client should just use the composed classes directly - it <em>must</em> do something new by combining that functionality.</p>
<p>There is the argument from the inheritance camp that pure delegation implementations suffer because they require lots of 'glue' methods which simply pass along values through a delegation 'chain'. However, this is simply reinventing an inheritance-like design using delegation. Programmers with too many years of exposure to inheritance-based designs are particularly vulnerable to falling into this trap, as, without realising it, they will think of how they would implement something using inheritance and then convert that to delegation.</p>
<p>Proper separation of concerns like the above code doesn't require glue methods, as each step is actually <em>adding value</em>, so they are not really 'glue' methods at all (if they don't add value, the design is flawed).</p>
<p>It boils down to this:</p>
<ul>
<li><p>For reusable code, each class should do only one thing
(and do it well). </p></li>
<li><p>Inheritance creates classes that do
more than one thing, because they are
mixed up with parent classes. </p></li>
<li><p>Therefore, using inheritance makes classes that are hard to reuse.</p></li>
</ul>
| 1 | 2009-07-01T20:55:23Z | [
"python",
"oop",
"inheritance"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 1,575,488 | <p>It's not inheritance that duck-typing makes pointless, it's interfaces â like the one you chose in creating an all abstract animal class.</p>
<p>If you had used an animal class that introduce some real behavior for its descendants to make use of, then dog and cat classes that introduced some additional behavior there would be a reason for both classes. It's only in the case of the ancestor class contributing no actual code to the descendant classes that your argument is correct.</p>
<p>Because Python can directly know the capabilities of any object, and because those capabilities are mutable beyond the class definition, the idea of using a pure abstract interface to "tell" the program what methods can be called is somewhat pointless. But that's not the sole, or even the main, point of inheritance.</p>
| 5 | 2009-10-15T22:28:31Z | [
"python",
"oop",
"inheritance"
] |
Whatâs the point of inheritance in Python? | 1,020,453 | <p>Suppose you have the following situation</p>
<pre><code>#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal &a) {
a.speak();
}
int main() {
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}
</code></pre>
<p>As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal âspeakâ and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.</p>
<p>But what about Python? Letâs see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:</p>
<pre><code>class Animal(object):
def speak(self):
raise NotImplementedError()
class Dog(Animal):
def speak(self):
print "woff!"
class Cat(Animal):
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals.
But in Python, thereâs no need for this hierarchy. This works equally well</p>
<pre><code>class Dog:
def speak(self):
print "woff!"
class Cat:
def speak(self):
print "meow"
def makeSpeak(a):
a.speak()
d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)
</code></pre>
<p>In Python you can send the signal âspeakâ to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it wonât compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.</p>
<p>On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...</p>
<p>What Iâd like to point out is that I havenât found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you donât need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.</p>
<p>So, in the end, the question stands: what's the point of inheritance in Python?</p>
<p><strong>Edit</strong>: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.</p>
<p>I also found <a href="http://forums.devshed.com/python-programming-11/does-interface-only-inheritance-make-sense-in-python-82822.html" rel="nofollow">a similar post</a> on this regard.</p>
| 69 | 2009-06-19T23:28:18Z | 11,434,605 | <p>Another small point is that op's 3'rd example, you can't call isinstance(). For example passing your 3'rd example to another object that takes and "Animal" type an calls speak on it. If you do it don't you would have to check for dog type, cat type, and so on. Not sure if instance checking is really "Pythonic", because of late binding. But then you would have to implement some way that the AnimalControl doesn't try to throw Cheeseburger types in the truck, becuase Cheeseburgers don't speak.</p>
<pre><code>class AnimalControl(object):
def __init__(self):
self._animalsInTruck=[]
def catachAnimal(self,animal):
if isinstance(animal,Animal):
animal.speak() #It's upset so it speak's/maybe it should be makesNoise
if not self._animalsInTruck.count <=10:
self._animalsInTruck.append(animal) #It's then put in the truck.
else:
#make note of location, catch you later...
else:
return animal #It's not an Animal() type / maybe return False/0/"message"
</code></pre>
| 1 | 2012-07-11T14:14:27Z | [
"python",
"oop",
"inheritance"
] |
Browser automation: Python + Firefox using PyXPCOM | 1,020,524 | <p>I have tried <a href="http://pamie.sourceforge.net/" rel="nofollow">Pamie</a> a browser automation library for internet explorer. It interfaces IE using COM, pretty neat:</p>
<pre><code>import PAM30
ie = PAM30.PAMIE("http://user-agent-string.info/")
ie.clickButton("Analyze my UA")
</code></pre>
<p>Now I would like to do the same thing using <a href="https://developer.mozilla.org/en/pyxpcom" rel="nofollow">PyXPCOM</a> with similar flexibility on Firefox. How can I do this? Can you provide sample code?</p>
<p><strong>update: please only pyxpcom</strong></p>
| 5 | 2009-06-19T23:50:57Z | 1,022,369 | <p>If you're testing a webapp and want to write Python to do it, check out <a href="http://seleniumhq.org/projects/remote-control/" rel="nofollow">Selenium RC</a> so you can use the same API for all browsers. </p>
| 2 | 2009-06-20T19:39:35Z | [
"python",
"firefox",
"automation"
] |
Browser automation: Python + Firefox using PyXPCOM | 1,020,524 | <p>I have tried <a href="http://pamie.sourceforge.net/" rel="nofollow">Pamie</a> a browser automation library for internet explorer. It interfaces IE using COM, pretty neat:</p>
<pre><code>import PAM30
ie = PAM30.PAMIE("http://user-agent-string.info/")
ie.clickButton("Analyze my UA")
</code></pre>
<p>Now I would like to do the same thing using <a href="https://developer.mozilla.org/en/pyxpcom" rel="nofollow">PyXPCOM</a> with similar flexibility on Firefox. How can I do this? Can you provide sample code?</p>
<p><strong>update: please only pyxpcom</strong></p>
| 5 | 2009-06-19T23:50:57Z | 1,022,375 | <p>I've used <a href="http://pypi.python.org/pypi/webdriver/0.5">webdriver</a> with firefox. I was very pleased with it.</p>
<p>As for the code examples, <a href="http://code.google.com/p/webdriver/wiki/PythonBindings">this</a> will get you started.</p>
| 10 | 2009-06-20T19:42:04Z | [
"python",
"firefox",
"automation"
] |
Browser automation: Python + Firefox using PyXPCOM | 1,020,524 | <p>I have tried <a href="http://pamie.sourceforge.net/" rel="nofollow">Pamie</a> a browser automation library for internet explorer. It interfaces IE using COM, pretty neat:</p>
<pre><code>import PAM30
ie = PAM30.PAMIE("http://user-agent-string.info/")
ie.clickButton("Analyze my UA")
</code></pre>
<p>Now I would like to do the same thing using <a href="https://developer.mozilla.org/en/pyxpcom" rel="nofollow">PyXPCOM</a> with similar flexibility on Firefox. How can I do this? Can you provide sample code?</p>
<p><strong>update: please only pyxpcom</strong></p>
| 5 | 2009-06-19T23:50:57Z | 1,057,354 | <p>My understanding of PyXPCOM is that it's meant to let you create and access XPCOM components, not control existing ones. You may not be able to do this using PyXPCOM at all, per Mark Hammond, the original author:</p>
<blockquote>
<p><a href="http://mail.python.org/pipermail/python-win32/2004-October/002569.html" rel="nofollow" title="Mark Hammond, 2004">It simply isn't what XPCOM is trying to do. I'm not sure if Mozilla/Firefox now has or is developing a COM or any other "automation" mechanism.</a></p>
</blockquote>
<p>and:</p>
<blockquote>
<p><a href="http://aspn.activestate.com/ASPN/Mail/Message/pyxpcom/3506917" rel="nofollow" title="Mark Hammond, 2007">If by "automating", you mean "controlling Mozilla via a remote process via xpcom", then as far as I know, that is not possible</a></p>
</blockquote>
<p>You may instead want to take a look at the previously-suggested Webdriver project, <a href="http://www.getwindmill.com/" rel="nofollow" title="Windmill">Windmill</a>, or <a href="http://code.google.com/p/mozmill/" rel="nofollow" title="MozMill">MozMill</a>, both of which support automating Firefox/Gecko/XULRunner via Python.</p>
| 4 | 2009-06-29T09:17:20Z | [
"python",
"firefox",
"automation"
] |
Is there a better way to convert a list to a dictionary in Python with keys but no values? | 1,020,722 | <p>I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values.</p>
<p>The only way I could find to do it was argued against.</p>
<p>"Using list comprehensions when the result is ignored is misleading and inefficient. A <code>for</code> loop is better"</p>
<pre><code>myList = ['a','b','c','d']
myDict = {}
x=[myDict.update({item:None}) for item in myList]
>>> myDict
{'a': None, 'c': None, 'b': None, 'd': None}
</code></pre>
<p>It works, but is there a better way to do this?</p>
| 6 | 2009-06-20T01:43:49Z | 1,020,724 | <p>Use <code>dict.fromkeys</code>:</p>
<pre><code>>>> my_list = [1, 2, 3]
>>> dict.fromkeys(my_list)
{1: None, 2: None, 3: None}
</code></pre>
<p>Values default to <code>None</code>, but you can specify them as an optional argument:</p>
<pre><code>>>> my_list = [1, 2, 3]
>>> dict.fromkeys(my_list, 0)
{1: 0, 2: 0, 3: 0}
</code></pre>
<p>From the docs:</p>
<blockquote>
<p>a.fromkeys(seq[, value]) Creates a new
dictionary with keys from seq and
values set to value.</p>
<p>dict.fromkeys is a class method that
returns a new dictionary. value
defaults to None. New in version 2.3.</p>
</blockquote>
| 22 | 2009-06-20T01:48:05Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] |
Is there a better way to convert a list to a dictionary in Python with keys but no values? | 1,020,722 | <p>I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values.</p>
<p>The only way I could find to do it was argued against.</p>
<p>"Using list comprehensions when the result is ignored is misleading and inefficient. A <code>for</code> loop is better"</p>
<pre><code>myList = ['a','b','c','d']
myDict = {}
x=[myDict.update({item:None}) for item in myList]
>>> myDict
{'a': None, 'c': None, 'b': None, 'd': None}
</code></pre>
<p>It works, but is there a better way to do this?</p>
| 6 | 2009-06-20T01:43:49Z | 1,020,728 | <p>You could use a <a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset">set</a> instead of a dict:</p>
<pre><code>>>> myList=['a','b','c','d']
>>> set(myList)
set(['a', 'c', 'b', 'd'])
</code></pre>
<p>This is better if you never need to store values, and are just storing an unordered collection of unique items.</p>
| 15 | 2009-06-20T01:49:34Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] |
Is there a better way to convert a list to a dictionary in Python with keys but no values? | 1,020,722 | <p>I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values.</p>
<p>The only way I could find to do it was argued against.</p>
<p>"Using list comprehensions when the result is ignored is misleading and inefficient. A <code>for</code> loop is better"</p>
<pre><code>myList = ['a','b','c','d']
myDict = {}
x=[myDict.update({item:None}) for item in myList]
>>> myDict
{'a': None, 'c': None, 'b': None, 'd': None}
</code></pre>
<p>It works, but is there a better way to do this?</p>
| 6 | 2009-06-20T01:43:49Z | 1,020,732 | <p>And here's a fairly wrong and inefficient way to do it using map:</p>
<pre><code>>>> d = dict()
>>> map (lambda x: d.__setitem__(x, None), [1,2,3])
[None, None, None]
>>> d
{1: None, 2: None, 3: None}
</code></pre>
| 1 | 2009-06-20T01:54:00Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] |
Is there a better way to convert a list to a dictionary in Python with keys but no values? | 1,020,722 | <p>I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values.</p>
<p>The only way I could find to do it was argued against.</p>
<p>"Using list comprehensions when the result is ignored is misleading and inefficient. A <code>for</code> loop is better"</p>
<pre><code>myList = ['a','b','c','d']
myDict = {}
x=[myDict.update({item:None}) for item in myList]
>>> myDict
{'a': None, 'c': None, 'b': None, 'd': None}
</code></pre>
<p>It works, but is there a better way to do this?</p>
| 6 | 2009-06-20T01:43:49Z | 1,021,036 | <p>To answer the original questioner's performance worries (for lookups in <code>dict</code> vs <code>set</code>), somewhat surprisingly, <code>dict</code> lookups <em>can</em> be minutely faster (in Python 2.5.1 on my rather slow laptop) assuming for example that half the lookups fail and half succeed. Here's how one goes about finding out:</p>
<pre><code>$ python -mtimeit -s'k=dict.fromkeys(range(99))' '5 in k and 112 in k'
1000000 loops, best of 3: 0.236 usec per loop
$ python -mtimeit -s'k=set(range(99))' '5 in k and 112 in k'
1000000 loops, best of 3: 0.265 usec per loop
</code></pre>
<p>doing each check several times to verify they're repeatable. So, if those 30 nanoseconds or less on a slow laptop are in an absolutely crucial bottleneck, it may be worth going for the obscure <code>dict.fromkeys</code> solution rather than the simple, obvious, readable, and clearly correct <code>set</code> (unusual -- almost invariably in Python the simple and direct solution has performance advantages too).</p>
<p>Of course, one needs to check with one's own Python version, machine, data, and ratio of successful vs failing tests, <strong>and</strong> confirm with extremely accurate profiling that shaving 30 nanoseconds (or whatever) off this lookup will make an important difference.</p>
<p>Fortunately, in the vast majority of cases, this will prove totally unnecessary... but since programmers <strong>will</strong> obsess about meaningless micro-optimizations <em>anyway</em>, no matter how many times they're told about their irrelevance, the <code>timeit</code> module is right there in the standard library to make those mostly-meaningless micro-benchmarks easy as pie anyway!-)</p>
| 5 | 2009-06-20T05:37:39Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] |
Is there a better way to convert a list to a dictionary in Python with keys but no values? | 1,020,722 | <p>I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values.</p>
<p>The only way I could find to do it was argued against.</p>
<p>"Using list comprehensions when the result is ignored is misleading and inefficient. A <code>for</code> loop is better"</p>
<pre><code>myList = ['a','b','c','d']
myDict = {}
x=[myDict.update({item:None}) for item in myList]
>>> myDict
{'a': None, 'c': None, 'b': None, 'd': None}
</code></pre>
<p>It works, but is there a better way to do this?</p>
| 6 | 2009-06-20T01:43:49Z | 1,021,116 | <p>You can use a list comprehension:</p>
<pre><code>my_list = ['a','b','c','d']
my_dict = dict([(ele, None) for ele in my_list])
</code></pre>
| 1 | 2009-06-20T07:04:57Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] |
Is there a better way to convert a list to a dictionary in Python with keys but no values? | 1,020,722 | <p>I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values.</p>
<p>The only way I could find to do it was argued against.</p>
<p>"Using list comprehensions when the result is ignored is misleading and inefficient. A <code>for</code> loop is better"</p>
<pre><code>myList = ['a','b','c','d']
myDict = {}
x=[myDict.update({item:None}) for item in myList]
>>> myDict
{'a': None, 'c': None, 'b': None, 'd': None}
</code></pre>
<p>It works, but is there a better way to do this?</p>
| 6 | 2009-06-20T01:43:49Z | 1,021,309 | <p>Maybe you can use itertools:</p>
<pre><code>>>>import itertools
>>>my_list = ['a','b','c','d']
>>>d = {}
>>>for x in itertools.imap(d.setdefault, my_list): pass
>>>print d
{'a': None, 'c': None, 'b': None, 'd': None}
</code></pre>
<p>For huge lists, maybe this is very good :P</p>
| 1 | 2009-06-20T09:33:52Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] |
Custom authentication in google app engine (python) | 1,020,736 | <p>Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?</p>
<p>I don't want to use google accounts for authentication and want to be able to create my own users.</p>
<p>If not specifically for google app engine, any resource on how to implement authentication using python and django?</p>
| 36 | 2009-06-20T01:56:48Z | 1,020,831 | <p>Well django 1.0 was updated today on Google AppEngine. But you can make user authentication like anything else you just can't really use sessions because it is so massive. </p>
<p>There is a session utility in <a href="http://gaeutilities.appspot.com/">http://gaeutilities.appspot.com/</a> </p>
<p><a href="http://gaeutilities.appspot.com/session">http://gaeutilities.appspot.com/session</a></p>
<p><a href="http://code.google.com/p/gaeutilities/">http://code.google.com/p/gaeutilities/</a></p>
<p>Or, </p>
<p>You have to create your own user tables and hash or encrypt passwords, then probably create a token system that mimics session with just a token hash or uuid cookie (sessions are just cookies anyways).</p>
<p>I have implemented a few with just basic google.webapp request and response headers. I typically use uuids for primary keys as the user id, then encrypt the user password and have their email for resets. </p>
<p>If you want to authorize users for external access to data you could look at OAuth for application access.</p>
<p>If you just want to store data by an id and it is more consumer facing, maybe just use openid like stackoverflow and then attach profile data to that identifier like django profiles (<a href="http://code.google.com/p/openid-selector/">http://code.google.com/p/openid-selector/</a>).</p>
<p>django 1.0 just came out today on GAE but I think the same problems exist, no sessions, you have to really create your own that store session data.</p>
| 19 | 2009-06-20T03:03:14Z | [
"python",
"google-app-engine",
"authentication"
] |
Custom authentication in google app engine (python) | 1,020,736 | <p>Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?</p>
<p>I don't want to use google accounts for authentication and want to be able to create my own users.</p>
<p>If not specifically for google app engine, any resource on how to implement authentication using python and django?</p>
| 36 | 2009-06-20T01:56:48Z | 1,020,836 | <p>The <a href="http://code.google.com/p/google-app-engine-samples/source/browse/#svn/trunk/openid-consumer" rel="nofollow">OpenID consumer</a> (part of the excellent "app engine samples" open source project) currently works (despite the warnings in its README, which is old) and would let you use OpenID for your users' logins.</p>
<p>django's <a href="http://docs.djangoproject.com/en/dev/topics/auth/" rel="nofollow">auth</a> is also usable, via e.g. <a href="http://code.google.com/p/google-app-engine-django/" rel="nofollow">this project</a> (at least the <code>users</code> part, not necessarily <code>groups</code> and <code>permissions</code> though they might get them working any time).</p>
| 8 | 2009-06-20T03:06:55Z | [
"python",
"google-app-engine",
"authentication"
] |
Custom authentication in google app engine (python) | 1,020,736 | <p>Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?</p>
<p>I don't want to use google accounts for authentication and want to be able to create my own users.</p>
<p>If not specifically for google app engine, any resource on how to implement authentication using python and django?</p>
| 36 | 2009-06-20T01:56:48Z | 1,298,669 | <p>Have a look <a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">app-engine-patch</a> for Django (your preferred framework I assume from your question). It offers authentication on gae.</p>
<p>Alternatively, take a look at <a href="http://www.web2py.com" rel="nofollow">web2py</a>. It's a Python-based framework that works on GAE and Relational databases. It's built-in Auth object provides for users, groups and permissions.</p>
<p>It doesn't give unbridled access to BigTable though, instead offering a subset of relational functionality (BigTable doesn't support Joins for example and web2py doesn't [yet] support BigTable models).</p>
<p>Support for BigTable is being discussed by both Web2py and Django communities.</p>
| 4 | 2009-08-19T09:11:06Z | [
"python",
"google-app-engine",
"authentication"
] |
Custom authentication in google app engine (python) | 1,020,736 | <p>Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?</p>
<p>I don't want to use google accounts for authentication and want to be able to create my own users.</p>
<p>If not specifically for google app engine, any resource on how to implement authentication using python and django?</p>
| 36 | 2009-06-20T01:56:48Z | 9,187,632 | <p>I saw that this pops up in google, every time you search "Custom login in app engine" so
I decided to give an answer that has been serving me.
Here is sample application
<a href="https://github.com/fredrikbonander/Webapp2-Sample-Applications">https://github.com/fredrikbonander/Webapp2-Sample-Applications</a></p>
<p>This uses</p>
<ol>
<li>webapp2 (already in GAE 1.6.2)</li>
<li>Jinja2 (already in GAE 1.6.2)</li>
</ol>
<p>Webapp2 seems to be the best bet for GAE (built on top of webapp hence future proof) so authentication using framework natively supported by GAE is a good idea. There are many
other frameworks but a lot of hacking has to be done on the users part to make them work. For people who want to build a "Stable" site, such hack work is extremely undesirable.</p>
<p>I also realize that SQL support for GAE is there now and django will be supported natively.
We all know django has built in user authentication system. Although, I think, especially in the cloud world NoSQL is the future. I am sure there will be a framework as good as django in the future for NoSQL. But thats me, your requirement might demand something else.</p>
| 8 | 2012-02-08T03:51:34Z | [
"python",
"google-app-engine",
"authentication"
] |
Custom authentication in google app engine (python) | 1,020,736 | <p>Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?</p>
<p>I don't want to use google accounts for authentication and want to be able to create my own users.</p>
<p>If not specifically for google app engine, any resource on how to implement authentication using python and django?</p>
| 36 | 2009-06-20T01:56:48Z | 10,318,234 | <p>This is a pretty out-of-the-box solution, and works pretty well:
<a href="http://code.scotchmedia.com/engineauth/docs/index.html">http://code.scotchmedia.com/engineauth/docs/index.html</a></p>
<p>It has built-in support for Facebook, Google+, Twitter, LinkedIn, GitHub and OpenId (via Google App Engine).</p>
<p>you just have to redirect the user to <code>/auth/facebook</code> or <code>/auth/google</code> and so on (this url is customizable).</p>
<p>It also implements two classes: <code>User</code> and <code>UserProfile</code>, every <code>User</code> is a unique account in your app and may relate to one or more <code>UserProfiles</code> -- which one is a login strategy that the unique <code>User</code> has to login into your app (if it's unclear, it's because my English is very bad, the <a href="http://code.scotchmedia.com/engineauth/docs/index.html">docs</a> explain better).</p>
<p>P.S.: The documentation is not very complete, but the code is pretty simple, short and self-explanatory. Also, there is a discussion <a href="https://groups.google.com/forum/#!topic/webapp2/Ui5FEFVnyIY">here</a> in which the author provides various answers to questions of confused and beggining users.</p>
| 10 | 2012-04-25T14:54:34Z | [
"python",
"google-app-engine",
"authentication"
] |
Custom authentication in google app engine (python) | 1,020,736 | <p>Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?</p>
<p>I don't want to use google accounts for authentication and want to be able to create my own users.</p>
<p>If not specifically for google app engine, any resource on how to implement authentication using python and django?</p>
| 36 | 2009-06-20T01:56:48Z | 10,318,522 | <p>In addition to all the other great answers, I would also add that <a href="https://developers.facebook.com/docs/authentication/" rel="nofollow">Facebook</a>, <a href="https://dev.twitter.com/docs/auth/oauth/single-user-with-examples" rel="nofollow">Twitter</a>, and <a href="http://github.com" rel="nofollow">github</a> all offer OAuth mechanisms that you can utilize as turn-key authentication support for your app.</p>
| 1 | 2012-04-25T15:10:52Z | [
"python",
"google-app-engine",
"authentication"
] |
Custom authentication in google app engine (python) | 1,020,736 | <p>Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?</p>
<p>I don't want to use google accounts for authentication and want to be able to create my own users.</p>
<p>If not specifically for google app engine, any resource on how to implement authentication using python and django?</p>
| 36 | 2009-06-20T01:56:48Z | 11,302,159 | <p>I googled around for a custom authenication system for app engine for a while. I eventually settled for running flask on app engine. I used this boilerplate for running flask on app engine <a href="https://github.com/kamalgill/flask-appengine-template/" rel="nofollow">https://github.com/kamalgill/flask-appengine-template/</a> and this flask auth extension <a href="http://pypi.python.org/pypi/Flask-Auth/" rel="nofollow">http://pypi.python.org/pypi/Flask-Auth/</a> which comes with plug and play google app engine support. I think flask also has a very nice oAuth library so eventually adding facebook and twitter logins will be easy</p>
| 2 | 2012-07-02T22:45:02Z | [
"python",
"google-app-engine",
"authentication"
] |
Custom authentication in google app engine (python) | 1,020,736 | <p>Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?</p>
<p>I don't want to use google accounts for authentication and want to be able to create my own users.</p>
<p>If not specifically for google app engine, any resource on how to implement authentication using python and django?</p>
| 36 | 2009-06-20T01:56:48Z | 11,701,813 | <p>Take a look at this project I am working on with coto: <a href="https://github.com/coto/gae-boilerplate" rel="nofollow">https://github.com/coto/gae-boilerplate</a> It includes a fully featured custom authentication system and much more.</p>
| 1 | 2012-07-28T14:21:57Z | [
"python",
"google-app-engine",
"authentication"
] |
Custom authentication in google app engine (python) | 1,020,736 | <p>Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?</p>
<p>I don't want to use google accounts for authentication and want to be able to create my own users.</p>
<p>If not specifically for google app engine, any resource on how to implement authentication using python and django?</p>
| 36 | 2009-06-20T01:56:48Z | 12,097,171 | <p>Another option is the <a href="http://beaker.readthedocs.org/en/latest/index.html" rel="nofollow">Beaker module</a>.
The AES encryption for client side sessions is nice.</p>
| 1 | 2012-08-23T17:34:18Z | [
"python",
"google-app-engine",
"authentication"
] |
Custom authentication in google app engine (python) | 1,020,736 | <p>Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?</p>
<p>I don't want to use google accounts for authentication and want to be able to create my own users.</p>
<p>If not specifically for google app engine, any resource on how to implement authentication using python and django?</p>
| 36 | 2009-06-20T01:56:48Z | 15,499,866 | <p>Here is an excellent and relatively recent (Jan 2013) blog post titled <a href="http://blog.abahgat.com/2013/01/07/user-authentication-with-webapp2-on-google-app-engine/">User authentication with webapp2 on Google App Engine</a>, and related <a href="https://github.com/abahgat/webapp2-user-accounts">GitHub repo: <code>abahgat/webapp2-user-accounts</code></a>.</p>
| 6 | 2013-03-19T12:44:15Z | [
"python",
"google-app-engine",
"authentication"
] |
Python database application frame work and tools | 1,020,775 | <p>I have been building business database applications such as finance, inventory and other business requirement applications. I am planning to shift to Python. What would be the tools to start with best. I would need to do master, transaction forms, processing (back end), reports and that sort of thing. The database would be postgress or mysql. As I am new to Python I understand that I need besides Python the ORM and also a frame work. My application is not a web site related but it could also be need to be done over the web if needed. </p>
<p>Pls help me to choose the initial setup of tool combinations, thanks in advance.</p>
<p>Sebj</p>
| 7 | 2009-06-20T02:22:57Z | 1,020,796 | <p>If I were you I would start with <a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">django</a>.</p>
| 3 | 2009-06-20T02:40:48Z | [
"python",
"frame"
] |
Python database application frame work and tools | 1,020,775 | <p>I have been building business database applications such as finance, inventory and other business requirement applications. I am planning to shift to Python. What would be the tools to start with best. I would need to do master, transaction forms, processing (back end), reports and that sort of thing. The database would be postgress or mysql. As I am new to Python I understand that I need besides Python the ORM and also a frame work. My application is not a web site related but it could also be need to be done over the web if needed. </p>
<p>Pls help me to choose the initial setup of tool combinations, thanks in advance.</p>
<p>Sebj</p>
| 7 | 2009-06-20T02:22:57Z | 1,020,822 | <p>As Boudewijn Rempt wrote <a href="http://www.informit.com/articles/article.aspx?p=30649&seqNum=7" rel="nofollow">here</a>, "for the easiest way to create a [[NON-web]] database application, you might want to take a look at <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQt</a>". He wrote this 6 years ago, but I think it's perfectly true today, too. pyqt4's <a href="http://docs.huihoo.com/pyqt/pyqt4/html/qtsql.html" rel="nofollow">QtSql</a> module, in particular, supports MySQL, PostgreSQL, and several other databases.</p>
| 1 | 2009-06-20T02:56:40Z | [
"python",
"frame"
] |
Python database application frame work and tools | 1,020,775 | <p>I have been building business database applications such as finance, inventory and other business requirement applications. I am planning to shift to Python. What would be the tools to start with best. I would need to do master, transaction forms, processing (back end), reports and that sort of thing. The database would be postgress or mysql. As I am new to Python I understand that I need besides Python the ORM and also a frame work. My application is not a web site related but it could also be need to be done over the web if needed. </p>
<p>Pls help me to choose the initial setup of tool combinations, thanks in advance.</p>
<p>Sebj</p>
| 7 | 2009-06-20T02:22:57Z | 1,021,065 | <p>If your application needs to work both on the desktop and on the web in the future, you can consider creating a web-based application with a distributable server. Such things are pretty easy to do with Python both in trivial ways and in more powerful ones such as using Twisted.</p>
<p>If desktop only is your direction, then indeed as Alex has said - go for PyQt. It's really easy to use and provides very powerful GUI capabilities with versatile DB bindings.</p>
<p>As for the DB - which one are you accustomed to using? If you're, say, a MySQL guru, it would be prudent to first of all check out Python's MySQL bindings. For an ORM definitely try SQLAlchemy.</p>
<p>Perhaps more details in the question can help providing a fuller answer.</p>
<p><hr /></p>
<p>More details (for your comment):</p>
<p>If PostgreSQL is your direction, Python has <a href="http://www.pygresql.org/" rel="nofollow">PyGreSQL</a> as a binding. It is open-source, like Python itself, so you should have no problem with cost-free applications for the user. As for Python being the right choice, I think it is. Consider that many powerful websites run Python (YouTube, Reddit, even Google for some applications). Python is also used in several high-volume applications such as the source control systems Mercurial and Bazaar, and the mailing list manager mailman.</p>
| 1 | 2009-06-20T06:13:06Z | [
"python",
"frame"
] |
Python database application frame work and tools | 1,020,775 | <p>I have been building business database applications such as finance, inventory and other business requirement applications. I am planning to shift to Python. What would be the tools to start with best. I would need to do master, transaction forms, processing (back end), reports and that sort of thing. The database would be postgress or mysql. As I am new to Python I understand that I need besides Python the ORM and also a frame work. My application is not a web site related but it could also be need to be done over the web if needed. </p>
<p>Pls help me to choose the initial setup of tool combinations, thanks in advance.</p>
<p>Sebj</p>
| 7 | 2009-06-20T02:22:57Z | 1,021,195 | <p>just FYI, for PyQT, the book has a chapter 15 with Databases, It looks good. and the book has something with data and view etc. I have read it and I think it's well worth your time:)</p>
| 0 | 2009-06-20T08:02:24Z | [
"python",
"frame"
] |
Python database application frame work and tools | 1,020,775 | <p>I have been building business database applications such as finance, inventory and other business requirement applications. I am planning to shift to Python. What would be the tools to start with best. I would need to do master, transaction forms, processing (back end), reports and that sort of thing. The database would be postgress or mysql. As I am new to Python I understand that I need besides Python the ORM and also a frame work. My application is not a web site related but it could also be need to be done over the web if needed. </p>
<p>Pls help me to choose the initial setup of tool combinations, thanks in advance.</p>
<p>Sebj</p>
| 7 | 2009-06-20T02:22:57Z | 1,021,313 | <p>If I were you, I would probably first look whether a web-based solution based on Django does the trick. If you need a little bit better look and feel, add jQuery to the mix. If it provides way too little functionality, go for PyQt. If you have a lot of very small applications, go for a mix of technologies. Below, you find my (somewhat lengthy) reasoning for this recommendation.</p>
<p><strong>Webapp vs. desktop application</strong></p>
<p>One year ago, we had a business db and needed a front-end. We had to decide what technology to use for the front-end. We considered: </p>
<ol>
<li><a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro">PyQt</a></li>
<li>Web-based (look <a href="http://wiki.python.org/moin/WebFrameworks">here</a> for an overview of web frame-works for Python)</li>
</ol>
<p>The advantages for PyQt from our perspective:</p>
<ul>
<li>Previous C++ experience with <a href="http://www.qtsoftware.com/products/">Qt</a> from which we knew that Qt is suited for the task.</li>
<li>All necessary tools included.</li>
<li>Easy to develop rich clients.</li>
</ul>
<p>We however decided against PyQt and for a web-based solution instead. Reasons were:</p>
<ul>
<li>The requirements for the front-end were modest and easy to do within a browser
(mostly reporting, some forms for entering data or running functions).</li>
<li>Deployment of the application (and new versions, bug fixes, etc.)
is much easier as everything only happens on the server in a controlled environment. </li>
<li>Access control / authentification / rights is "for free" as it is part of the server (in our case Apache using Active Directory Authentification) and the browser, which is important for us.</li>
<li>The application needed server connection anyways and didn't have to store anything on the client's side.</li>
</ul>
<p><em>In a nutshell</em>: feature-rich front-ends with a lot of functionality in a controlled deployment environment are probably easier to implement with Qt. For our light-weight front-ends, a server-based solution seemed better to us.</p>
<p><strong>Which web framework?</strong></p>
<p>Now that we had decided on a technology, we had to choose a framework. We researched a bit, and looked at two alternatives in detail:</p>
<ol>
<li><a href="http://www.djangoproject.com/">Django</a></li>
<li>A stack of software consisting of <a href="http://www.cherrypy.org/">CherryPy</a> as dispatcher (to match http requests to functionality and all the related stuff), <a href="http://www.makotemplates.org/">Mako</a> as a templating library to generate web-pages, <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> as an ORM, and <a href="http://jquery.com/">jQuery</a> for client-side functionality.</li>
</ol>
<p>We evaluated the two alternatives, and at the end settled for the second one. The decision was driven by our really "light-light-weight" front-end requirements (a lot of very small applications). A stack of software - which we can mix and match as needed - seemed better to us. We can re-use SQLAlchemy in situations, where we don't need a web-front-end, we can just use CherryPy without a templating library and a ORM, and so on. In many other cases, I would however choose Django over this stack.</p>
<p><strong>To sum up:</strong></p>
<ul>
<li>one big, complex application -> PyQt</li>
<li>a set of relativily similar, straigtforward reports, forms, etc. with one look-and-feel -> Django</li>
<li>a relatively diverse set of things that differ widely in requirements and used technology or re-use of some technology in other circumstances -> mix of technologies as needed</li>
</ul>
| 9 | 2009-06-20T09:37:32Z | [
"python",
"frame"
] |
When you write a Titanium app, is the source code visible to users? | 1,020,838 | <p>When you write an HTML/CSS/JavaScript app for Adobe AIR, the source files sit in a directory visible to anyone who looks.</p>
<p><a href="http://www.appcelerator.com/products/titanium-desktop/" rel="nofollow">Appcelerator Titanium</a> lets you code in JavaScript, Python, and Ruby. Is the bundling similar to AIR, with all the source exposed?</p>
| 2 | 2009-06-20T03:08:01Z | 1,026,147 | <p>According to the <a href="http://titaniumapp.com/faq/if-i-build-my-app-in-titanium-and-distribute-it-is-the-source-code-visible-to-the-user-in-other-words-can-the-program-be-compiled-into-a-binary-format">Titanium FAQ</a>, yes, your source code will be accessible to anyone who looks for it.</p>
| 5 | 2009-06-22T08:54:22Z | [
"javascript",
"python",
"ruby",
"ria",
"titanium"
] |
When you write a Titanium app, is the source code visible to users? | 1,020,838 | <p>When you write an HTML/CSS/JavaScript app for Adobe AIR, the source files sit in a directory visible to anyone who looks.</p>
<p><a href="http://www.appcelerator.com/products/titanium-desktop/" rel="nofollow">Appcelerator Titanium</a> lets you code in JavaScript, Python, and Ruby. Is the bundling similar to AIR, with all the source exposed?</p>
| 2 | 2009-06-20T03:08:01Z | 3,013,019 | <p>As <a href="http://stackoverflow.com/users/61027/nosredna">Nosredna</a> added in the comment they seem to have gotten arround to that change in their newer framework versions. </p>
<p>Look at this <a href="http://stackoverflow.com/questions/2444001/how-does-appcelerator-titanium-mobile-work">question</a> to get some insight from an appcelerator found on how the framework works. I understand this as a compilation process that won't leave a trace of your js files in the package. </p>
| 2 | 2010-06-10T09:04:43Z | [
"javascript",
"python",
"ruby",
"ria",
"titanium"
] |
How to make a simple command-line chat in Python? | 1,020,839 | <p>I study network programming and would like to write a simple command-line chat in Python.</p>
<p>I'm wondering how make receving constant along with inputing available for sending at any time. </p>
<p>As you see, this client can do only one job at a time:</p>
<pre><code>from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while 1:
data = raw_input('> ')
if not data: break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZE)
if not data: break
print data
tcpCliSock.close()
</code></pre>
<p>So if another client sends a message, this client will only receive it after sending a message too. I bet you understand me. I have googled for the matter and found out many interesting things such as asynchronous I/O, threading, non-blocking synchronization, concurrent programming and so on. I have also installed the twisted package. In brief, I've been learning all these things but yet haven't found what I was looking for. (Of course, I will keep trying and trying until I get to the point.)</p>
<p>So, my question is how make that? =) </p>
| 10 | 2009-06-20T03:08:03Z | 1,020,852 | <p>If you want to code it from scratch <code>select</code> is the way to go (and you can read on Google Book Search most of the chapter of Python in a Nutshell that covers such matters); if you want to leverage more abstraction, <code>asyncore</code> is usable, but <a href="http://twistedmatrix.com/trac/">Twisted</a> is much richer and more powerful.</p>
| 5 | 2009-06-20T03:12:45Z | [
"python"
] |
How to make a simple command-line chat in Python? | 1,020,839 | <p>I study network programming and would like to write a simple command-line chat in Python.</p>
<p>I'm wondering how make receving constant along with inputing available for sending at any time. </p>
<p>As you see, this client can do only one job at a time:</p>
<pre><code>from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while 1:
data = raw_input('> ')
if not data: break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZE)
if not data: break
print data
tcpCliSock.close()
</code></pre>
<p>So if another client sends a message, this client will only receive it after sending a message too. I bet you understand me. I have googled for the matter and found out many interesting things such as asynchronous I/O, threading, non-blocking synchronization, concurrent programming and so on. I have also installed the twisted package. In brief, I've been learning all these things but yet haven't found what I was looking for. (Of course, I will keep trying and trying until I get to the point.)</p>
<p>So, my question is how make that? =) </p>
| 10 | 2009-06-20T03:08:03Z | 1,020,853 | <p>You should use <a href="http://linux.die.net/man/2/select" rel="nofollow">select</a>.</p>
<p>Check:</p>
<ul>
<li><a href="http://docs.python.org/library/select.html" rel="nofollow">Another select link</a></li>
<li><a href="http://www.amk.ca/python/howto/sockets/" rel="nofollow">howto</a></li>
</ul>
| 1 | 2009-06-20T03:14:06Z | [
"python"
] |
How to make a simple command-line chat in Python? | 1,020,839 | <p>I study network programming and would like to write a simple command-line chat in Python.</p>
<p>I'm wondering how make receving constant along with inputing available for sending at any time. </p>
<p>As you see, this client can do only one job at a time:</p>
<pre><code>from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while 1:
data = raw_input('> ')
if not data: break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZE)
if not data: break
print data
tcpCliSock.close()
</code></pre>
<p>So if another client sends a message, this client will only receive it after sending a message too. I bet you understand me. I have googled for the matter and found out many interesting things such as asynchronous I/O, threading, non-blocking synchronization, concurrent programming and so on. I have also installed the twisted package. In brief, I've been learning all these things but yet haven't found what I was looking for. (Of course, I will keep trying and trying until I get to the point.)</p>
<p>So, my question is how make that? =) </p>
| 10 | 2009-06-20T03:08:03Z | 1,020,859 | <p>I wrote one in async I/O... its a lot easier to wrap your head around than a full threading model.</p>
<p>if you can get your hands ahold of "talk"'s source code, you can learn a lot about it. see a demo <a href="http://dsl.org/cookbook/cookbook_40.html#SEC559" rel="nofollow">http://dsl.org/cookbook/cookbook_40.html#SEC559</a> , or try it your self if you are on a linux box...</p>
<p>it sends characters in real-time.</p>
<p>also, ytalk is interactive and multiple users.... kinda like hudddlechat or campfire.</p>
| 1 | 2009-06-20T03:19:09Z | [
"python"
] |
How to make a simple command-line chat in Python? | 1,020,839 | <p>I study network programming and would like to write a simple command-line chat in Python.</p>
<p>I'm wondering how make receving constant along with inputing available for sending at any time. </p>
<p>As you see, this client can do only one job at a time:</p>
<pre><code>from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while 1:
data = raw_input('> ')
if not data: break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZE)
if not data: break
print data
tcpCliSock.close()
</code></pre>
<p>So if another client sends a message, this client will only receive it after sending a message too. I bet you understand me. I have googled for the matter and found out many interesting things such as asynchronous I/O, threading, non-blocking synchronization, concurrent programming and so on. I have also installed the twisted package. In brief, I've been learning all these things but yet haven't found what I was looking for. (Of course, I will keep trying and trying until I get to the point.)</p>
<p>So, my question is how make that? =) </p>
| 10 | 2009-06-20T03:08:03Z | 1,021,399 | <p>Chat programs are doing two things concurrently.</p>
<ol>
<li><p>Watching the local user's keyboard and sending to the remote user (via a socket of some kind)</p></li>
<li><p>Watching the remote socket and displaying what they type on the local console.</p></li>
</ol>
<p>You have several ways to do this.</p>
<ol>
<li><p>A program that opens socket and keyboard and uses the <a href="http://docs.python.org/library/select.html" rel="nofollow">select</a> module to see which one has input ready.</p></li>
<li><p>A program that creates two threads. One threads reads the remote socket and prints. The other thread reads the keyboard and sends to the remote socket.</p></li>
<li><p>A program that forks two subprocesses. One subprocess reads the remote socket and prints. The other subprocess reads the keyboard and sends to the remote socket.</p></li>
</ol>
| 1 | 2009-06-20T10:45:08Z | [
"python"
] |
How to make a simple command-line chat in Python? | 1,020,839 | <p>I study network programming and would like to write a simple command-line chat in Python.</p>
<p>I'm wondering how make receving constant along with inputing available for sending at any time. </p>
<p>As you see, this client can do only one job at a time:</p>
<pre><code>from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while 1:
data = raw_input('> ')
if not data: break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZE)
if not data: break
print data
tcpCliSock.close()
</code></pre>
<p>So if another client sends a message, this client will only receive it after sending a message too. I bet you understand me. I have googled for the matter and found out many interesting things such as asynchronous I/O, threading, non-blocking synchronization, concurrent programming and so on. I have also installed the twisted package. In brief, I've been learning all these things but yet haven't found what I was looking for. (Of course, I will keep trying and trying until I get to the point.)</p>
<p>So, my question is how make that? =) </p>
| 10 | 2009-06-20T03:08:03Z | 1,021,683 | <p>Well, well, here's what I am having at this very moment.</p>
<p>Server goes like this:</p>
<pre><code>import asyncore
import socket
clients = {}
class MainServerSocket(asyncore.dispatcher):
def __init__(self, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(('',port))
self.listen(5)
def handle_accept(self):
newSocket, address = self.accept( )
clients[address] = newSocket
print "Connected from", address
SecondaryServerSocket(newSocket)
class SecondaryServerSocket(asyncore.dispatcher_with_send):
def handle_read(self):
receivedData = self.recv(8192)
if receivedData:
every = clients.values()
for one in every:
one.send(receivedData+'\n')
else: self.close( )
def handle_close(self):
print "Disconnected from", self.getpeername( )
one = self.getpeername( )
del clients[one]
MainServerSocket(21567)
asyncore.loop( )
</code></pre>
<p>And client goes just like this:</p>
<pre><code>from Tkinter import *
from socket import *
import thread
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
self.socket()
def callback(self, event):
message = self.entry_field.get()
tcpCliSock.send(message)
def create_widgets(self):
self.messaging_field = Text(self, width = 110, height = 20, wrap = WORD)
self.messaging_field.grid(row = 0, column = 0, columnspan = 2, sticky = W)
self.entry_field = Entry(self, width = 92)
self.entry_field.grid(row = 1, column = 0, sticky = W)
self.entry_field.bind('<Return>', self.callback)
def add(self, data):
self.messaging_field.insert(END, data)
def socket(self):
def loop0():
while 1:
data = tcpCliSock.recv(BUFSIZE)
if data: self.add(data)
thread.start_new_thread(loop0, ())
root = Tk()
root.title("Chat client")
root.geometry("550x260")
app = Application(root)
root.mainloop()
</code></pre>
<p>Now it's time to make the code look better and add some functionality.</p>
<p>Thanks for your help, folks!</p>
| 2 | 2009-06-20T13:58:47Z | [
"python"
] |
How to make a simple command-line chat in Python? | 1,020,839 | <p>I study network programming and would like to write a simple command-line chat in Python.</p>
<p>I'm wondering how make receving constant along with inputing available for sending at any time. </p>
<p>As you see, this client can do only one job at a time:</p>
<pre><code>from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while 1:
data = raw_input('> ')
if not data: break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZE)
if not data: break
print data
tcpCliSock.close()
</code></pre>
<p>So if another client sends a message, this client will only receive it after sending a message too. I bet you understand me. I have googled for the matter and found out many interesting things such as asynchronous I/O, threading, non-blocking synchronization, concurrent programming and so on. I have also installed the twisted package. In brief, I've been learning all these things but yet haven't found what I was looking for. (Of course, I will keep trying and trying until I get to the point.)</p>
<p>So, my question is how make that? =) </p>
| 10 | 2009-06-20T03:08:03Z | 1,023,232 | <p>Your question was not very coherent. However, your program does not need to be asynchronous at all to attain what you are asking for.</p>
<p>This is a working chat script you originally wanted with minimal changes. It uses 1 thread for receiving and 1 for sending, both using blocking sockets. It is far simpler than using asynchronous methods.</p>
<pre><code>from socket import *
from threading import Thread
import sys
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
def recv():
while True:
data = tcpCliSock.recv(BUFSIZE)
if not data: sys.exit(0)
print data
Thread(target=recv).start()
while True:
data = raw_input('> ')
if not data: break
tcpCliSock.send(data)
tcpCliSock.close()
</code></pre>
| 7 | 2009-06-21T04:52:44Z | [
"python"
] |
urllib2 read to Unicode | 1,020,892 | <p>I need to store the content of a site that can be in any language. And I need to be able to search the content for a Unicode string.</p>
<p>I have tried something like:</p>
<pre><code>import urllib2
req = urllib2.urlopen('http://lenta.ru')
content = req.read()
</code></pre>
<p>The content is a byte stream, so I can search it for a Unicode string.</p>
<p>I need some way that when I do <code>urlopen</code> and then read to use the charset from the headers to decode the content and encode it into UTF-8.</p>
| 42 | 2009-06-20T03:46:27Z | 1,020,931 | <p>After the operations you performed, you'll see:</p>
<pre><code>>>> req.headers['content-type']
'text/html; charset=windows-1251'
</code></pre>
<p>and so:</p>
<pre><code>>>> encoding=req.headers['content-type'].split('charset=')[-1]
>>> ucontent = unicode(content, encoding)
</code></pre>
<p><code>ucontent</code> is now a Unicode string (of 140655 characters) -- so for example to display a part of it, if your terminal is UTF-8:</p>
<pre><code>>>> print ucontent[76:110].encode('utf-8')
<title>Lenta.ru: Ðлавное: </title>
</code></pre>
<p>and you can search, etc, etc.</p>
<p>Edit: Unicode I/O is usually tricky (this may be what's holding up the original asker) but I'm going to bypass the difficult problem of inputting Unicode strings to an interactive Python interpreter (completely unrelated to the original question) to show how, once a Unicode string IS correctly input (I'm doing it by codepoints -- goofy but not tricky;-), search is absolutely a no-brainer (and thus hopefully the original question has been thoroughly answered). Again assuming a UTF-8 terminal:</p>
<pre><code>>>> x=u'\u0413\u043b\u0430\u0432\u043d\u043e\u0435'
>>> print x.encode('utf-8')
Ðлавное
>>> x in ucontent
True
>>> ucontent.find(x)
93
</code></pre>
<p><strong>Note</strong>: Keep in mind that this method may not work for all sites, since some sites only specify character encoding inside the served documents (using http-equiv meta tags, for example).</p>
| 90 | 2009-06-20T04:17:41Z | [
"python",
"unicode",
"urllib2"
] |
urllib2 read to Unicode | 1,020,892 | <p>I need to store the content of a site that can be in any language. And I need to be able to search the content for a Unicode string.</p>
<p>I have tried something like:</p>
<pre><code>import urllib2
req = urllib2.urlopen('http://lenta.ru')
content = req.read()
</code></pre>
<p>The content is a byte stream, so I can search it for a Unicode string.</p>
<p>I need some way that when I do <code>urlopen</code> and then read to use the charset from the headers to decode the content and encode it into UTF-8.</p>
| 42 | 2009-06-20T03:46:27Z | 20,714,761 | <p>To parse <code>Content-Type</code> http header, you could use <code>cgi.parse_header</code> function:</p>
<pre><code>import cgi
import urllib2
r = urllib2.urlopen('http://lenta.ru')
_, params = cgi.parse_header(r.headers.get('Content-Type', ''))
encoding = params.get('charset', 'utf-8')
unicode_text = r.read().decode(encoding)
</code></pre>
<p>Another way to get the charset:</p>
<pre><code>>>> import urllib2
>>> r = urllib2.urlopen('http://lenta.ru')
>>> r.headers.getparam('charset')
'utf-8'
</code></pre>
<p>Or in Python 3:</p>
<pre><code>>>> import urllib.request
>>> r = urllib.request.urlopen('http://lenta.ru')
>>> r.headers.get_content_charset()
'utf-8'
</code></pre>
<p>Character encoding can also be specified inside html document e.g., <code><meta charset="utf-8"></code>.</p>
| 8 | 2013-12-21T02:23:33Z | [
"python",
"unicode",
"urllib2"
] |
Interacting with another command line program in Python | 1,020,980 | <p>I need to write a Python script that can run another command line program and interact with it's stdin and stdout streams. Essentially, the Python script will read from the target command line program, intelligently respond by writing to its stdin, and then read the results from the program again. (It would do this repeatedly.)</p>
<p>I've looked through the subprocess module, and I can't seem to get it to do this read/write/read/write thing that I'm looking for. Is there something else I should be trying?</p>
| 6 | 2009-06-20T05:01:10Z | 1,020,991 | <p>see the question
<a href="http://stackoverflow.com/questions/989129/wxpython-how-to-create-a-bash-shell-window/1005079#1005079">http://stackoverflow.com/questions/989129/wxpython-how-to-create-a-bash-shell-window/1005079#1005079</a></p>
<p>there I have given a full fledged interaction with bash shell
reading stdout and stderr and communicating via stdin</p>
<p>main part is extension of this code</p>
<pre><code>bp = Popen('bash', shell=False, stdout=PIPE, stdin=PIPE, stderr=PIPE)
bp.stdin.write("ls\n")
bp.stdout.readline()
</code></pre>
<p>if we read all data it will get blocked so the link to script I have given does it in a thread. That is a complete wxpython app mimicking bash shell partially.</p>
| 2 | 2009-06-20T05:06:06Z | [
"python",
"command-line",
"subprocess"
] |
Interacting with another command line program in Python | 1,020,980 | <p>I need to write a Python script that can run another command line program and interact with it's stdin and stdout streams. Essentially, the Python script will read from the target command line program, intelligently respond by writing to its stdin, and then read the results from the program again. (It would do this repeatedly.)</p>
<p>I've looked through the subprocess module, and I can't seem to get it to do this read/write/read/write thing that I'm looking for. Is there something else I should be trying?</p>
| 6 | 2009-06-20T05:01:10Z | 1,021,001 | <p>To perform such detailed interaction (when, outside of your control, the other program may be buffering its output unless it thinks it's talking to a terminal) needs something like <a href="http://pexpect.sourceforge.net/pexpect.html">pexpect</a> -- which in turns requires <code>pty</code>, a Python standard library module that (on operating systems that allow it, such as Linux and Mac OS x) implements "pseudo-terminals".</p>
<p>Life is harder on Windows, but maybe <a href="http://sage.math.washington.edu/home/goreckc/sage/wexpect/wexpect.zip">this zipfile</a> can help -- it's supposed to be a port of <code>pexpect</code> to Windows (sorry, I have no Windows machine to check it on). The project in question, called <code>wexpect</code>, lives <a href="http://code.google.com/p/wexpect/">here</a>.</p>
| 6 | 2009-06-20T05:12:42Z | [
"python",
"command-line",
"subprocess"
] |
Package for creating and validating HTML forms in Python? - to be used in Google Appengine | 1,021,411 | <p>Is there a well maintained package available in Python for creating and validating HTML forms? I will deploying it finally on Google Appengine.</p>
| 1 | 2009-06-20T11:01:14Z | 1,021,454 | <p>AppEngine includes Django's form framework (or a variation thereof), which I find very nice. It also plays well with your ORM (i.e. getting forms for models is very DRY). The only potential problem is the lack of client-side validation.</p>
| 0 | 2009-06-20T11:29:34Z | [
"python",
"html",
"google-app-engine",
"forms"
] |
Package for creating and validating HTML forms in Python? - to be used in Google Appengine | 1,021,411 | <p>Is there a well maintained package available in Python for creating and validating HTML forms? I will deploying it finally on Google Appengine.</p>
| 1 | 2009-06-20T11:01:14Z | 1,021,470 | <p>For client-side validation, check <a href="http://plugins.jquery.com/search/node/form%2Bvalidate" rel="nofollow">http://plugins.jquery.com/search/node/form+validate</a>;
for server-side, actually ALMOST every web framework (web.py, django, etc.) has its own form generation as well as validation lib for you to use.</p>
| 2 | 2009-06-20T11:41:10Z | [
"python",
"html",
"google-app-engine",
"forms"
] |
Package for creating and validating HTML forms in Python? - to be used in Google Appengine | 1,021,411 | <p>Is there a well maintained package available in Python for creating and validating HTML forms? I will deploying it finally on Google Appengine.</p>
| 1 | 2009-06-20T11:01:14Z | 1,021,930 | <p>You can use <a href="http://code.google.com/appengine/articles/djangoforms.html" rel="nofollow">Django form validation</a> on GAE storage via <code>db.djangoforms.ModelForm</code>.</p>
<p>To smoothly integrate client-side <a href="http://www.dojotoolkit.org/" rel="nofollow">Dojo</a> functionality with Django server-side web apps, I'd look at <a href="http://code.google.com/p/dojango/" rel="nofollow">dojango</a>, which does work fine with GAE (as well as without). However, dojango (currently at release 0.3.1) does not yet automatically provide client-side validation of Django forms -- that's on the roadmap for the forthcoming release 0.4 of dojango, but I have no idea about the timeframe in which you could expect it.</p>
| 2 | 2009-06-20T16:15:31Z | [
"python",
"html",
"google-app-engine",
"forms"
] |
How to call a property of the base class if this property is being overwritten in the derived class? | 1,021,464 | <p>I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.</p>
<p>But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties? How to call the property getter or setter from the base class?</p>
<p>Of course just calling the attribute itself gives infinite recursion.</p>
<pre><code>class Foo(object):
@property
def bar(self):
return 5
@bar.setter
def bar(self, a):
print a
class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return self.bar # --> recursion!
@bar.setter
def bar(self, c):
# perform the same action
# as in the base class
self.bar = c # --> recursion!
# then do something else
print 'something else'
fb = FooBar()
fb.bar = 7
</code></pre>
| 50 | 2009-06-20T11:37:14Z | 1,021,477 | <p><a href="http://docs.python.org/3.0/library/functions.html?highlight=super#super">Super</a> should do the trick:</p>
<pre><code>return super().bar
</code></pre>
<p>In Python 2.x you need to use the more verbose syntax:</p>
<pre><code>return super(FooBar, self).bar
</code></pre>
| 26 | 2009-06-20T11:46:49Z | [
"python",
"inheritance",
"properties",
"overloading",
"descriptor"
] |
How to call a property of the base class if this property is being overwritten in the derived class? | 1,021,464 | <p>I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.</p>
<p>But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties? How to call the property getter or setter from the base class?</p>
<p>Of course just calling the attribute itself gives infinite recursion.</p>
<pre><code>class Foo(object):
@property
def bar(self):
return 5
@bar.setter
def bar(self, a):
print a
class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return self.bar # --> recursion!
@bar.setter
def bar(self, c):
# perform the same action
# as in the base class
self.bar = c # --> recursion!
# then do something else
print 'something else'
fb = FooBar()
fb.bar = 7
</code></pre>
| 50 | 2009-06-20T11:37:14Z | 1,021,482 | <p>try</p>
<pre><code>@property
def bar:
return super(FooBar, self).bar
</code></pre>
<p>Although I'm not sure if python supports calling the base class property. A property is actually a callable object which is set up with the function specified and then replaces that name in the class. This could easily mean that there is no super function available.</p>
<p>You could always switch your syntax to use the property() function though:</p>
<pre><code>class Foo(object):
def _getbar(self):
return 5
def _setbar(self, a):
print a
bar = property(_getbar, _setbar)
class FooBar(Foo):
def _getbar(self):
# return the same value
# as in the base class
return super(FooBar, self)._getbar()
def bar(self, c):
super(FooBar, self)._setbar(c)
print "Something else"
bar = property(_getbar, _setbar)
fb = FooBar()
fb.bar = 7
</code></pre>
| 4 | 2009-06-20T11:50:09Z | [
"python",
"inheritance",
"properties",
"overloading",
"descriptor"
] |
How to call a property of the base class if this property is being overwritten in the derived class? | 1,021,464 | <p>I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.</p>
<p>But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties? How to call the property getter or setter from the base class?</p>
<p>Of course just calling the attribute itself gives infinite recursion.</p>
<pre><code>class Foo(object):
@property
def bar(self):
return 5
@bar.setter
def bar(self, a):
print a
class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return self.bar # --> recursion!
@bar.setter
def bar(self, c):
# perform the same action
# as in the base class
self.bar = c # --> recursion!
# then do something else
print 'something else'
fb = FooBar()
fb.bar = 7
</code></pre>
| 50 | 2009-06-20T11:37:14Z | 1,021,484 | <p>You might think you could call the base class function which is called by property:</p>
<pre><code>class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return Foo.bar(self)
</code></pre>
<p>Though this is the most obvious thing to try I think - <strong>it does not work because bar is a property, not a callable.</strong> </p>
<p>But a property is just an object, with a getter method to find the corresponding attribute:</p>
<pre><code>class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return Foo.bar.fget(self)
</code></pre>
| 55 | 2009-06-20T11:51:38Z | [
"python",
"inheritance",
"properties",
"overloading",
"descriptor"
] |
How to call a property of the base class if this property is being overwritten in the derived class? | 1,021,464 | <p>I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.</p>
<p>But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties? How to call the property getter or setter from the base class?</p>
<p>Of course just calling the attribute itself gives infinite recursion.</p>
<pre><code>class Foo(object):
@property
def bar(self):
return 5
@bar.setter
def bar(self, a):
print a
class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return self.bar # --> recursion!
@bar.setter
def bar(self, c):
# perform the same action
# as in the base class
self.bar = c # --> recursion!
# then do something else
print 'something else'
fb = FooBar()
fb.bar = 7
</code></pre>
| 50 | 2009-06-20T11:37:14Z | 1,021,485 | <pre><code> class Base(object):
def method(self):
print "Base method was called"
class Derived(Base):
def method(self):
super(Derived,self).method()
print "Derived method was called"
d = Derived()
d.method()
</code></pre>
<p>(that is unless I am missing something from your explanation)</p>
| -1 | 2009-06-20T11:51:44Z | [
"python",
"inheritance",
"properties",
"overloading",
"descriptor"
] |
How to call a property of the base class if this property is being overwritten in the derived class? | 1,021,464 | <p>I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.</p>
<p>But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties? How to call the property getter or setter from the base class?</p>
<p>Of course just calling the attribute itself gives infinite recursion.</p>
<pre><code>class Foo(object):
@property
def bar(self):
return 5
@bar.setter
def bar(self, a):
print a
class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return self.bar # --> recursion!
@bar.setter
def bar(self, c):
# perform the same action
# as in the base class
self.bar = c # --> recursion!
# then do something else
print 'something else'
fb = FooBar()
fb.bar = 7
</code></pre>
| 50 | 2009-06-20T11:37:14Z | 37,663,266 | <p>There is an alternative using <code>super</code> that does not require to explicitly reference the base class name.</p>
<h2>Base class A:</h2>
<pre class="lang-py prettyprint-override"><code>class A(object):
def __init__(self):
self._prop = None
@property
def prop(self):
return self._prop
@prop.setter
def prop(self, value):
self._prop = value
class B(A):
# we want to extend prop here
pass
</code></pre>
<h2>In B, accessing the property getter of the parent class A:</h2>
<p>As others have already answered, it's:</p>
<pre><code>super(B, self).prop
</code></pre>
<p>Or in Python 3:</p>
<pre><code>super().prop
</code></pre>
<p>This returns the value returned by the getter of the property, not the getter itself but it's sufficient to extend the getter.</p>
<h2>In B, accessing the property setter of the parent class A:</h2>
<p>The best recommendation I've seen so far is the following:</p>
<pre><code>A.prop.fset(self, value)
</code></pre>
<p>I believe this one is better:</p>
<pre><code>super(B, self.__class__).prop.fset(self, value)
</code></pre>
<p>In this example both options are equivalent but using super has the advantage of being independent from the base classes of <code>B</code>. If <code>B</code> were to inherit from a <code>C</code> class also extending the property, you would not have to update <code>B</code>'s code.</p>
<h2>Full code of B extending A's property:</h2>
<pre class="lang-py prettyprint-override"><code>class B(A):
@property
def prop(self):
value = super(B, self).prop
# do something with / modify value here
return value
@prop.setter
def prop(self, value):
# do something with / modify value here
return super(B, self.__class__).prop.fset(self, value)
</code></pre>
<h2>One caveat:</h2>
<p>Unless your property doesn't have a setter, you have to define both the setter and the getter in <code>B</code> even if you only change the behaviour of one of them.</p>
| 5 | 2016-06-06T17:14:41Z | [
"python",
"inheritance",
"properties",
"overloading",
"descriptor"
] |
Problem with exiting a daemonized process | 1,021,613 | <p>I am writing a daemon program that spawns several other children processes. After I run the <code>stop</code> script, the main process keeps running when it's intended to quit, this really confused me.</p>
<pre><code>import daemon, signal
from multiprocessing import Process, cpu_count, JoinableQueue
from http import httpserv
from worker import work
class Manager:
"""
This manager starts the http server processes and worker
processes, creates the input/output queues that keep the processes
work together nicely.
"""
def __init__(self):
self.NUMBER_OF_PROCESSES = cpu_count()
def start(self):
self.i_queue = JoinableQueue()
self.o_queue = JoinableQueue()
# Create worker processes
self.workers = [Process(target=work,
args=(self.i_queue, self.o_queue))
for i in range(self.NUMBER_OF_PROCESSES)]
for w in self.workers:
w.daemon = True
w.start()
# Create the http server process
self.http = Process(target=httpserv, args=(self.i_queue, self.o_queue))
self.http.daemon = True
self.http.start()
# Keep the current process from returning
self.running = True
while self.running:
time.sleep(1)
def stop(self):
print "quiting ..."
# Stop accepting new requests from users
os.kill(self.http.pid, signal.SIGINT)
# Waiting for all requests in output queue to be delivered
self.o_queue.join()
# Put sentinel None to input queue to signal worker processes
# to terminate
self.i_queue.put(None)
for w in self.workers:
w.join()
self.i_queue.join()
# Let main process return
self.running = False
import daemon
manager = Manager()
context = daemon.DaemonContext()
context.signal_map = {
signal.SIGHUP: lambda signum, frame: manager.stop(),
}
context.open()
manager.start()
</code></pre>
<p>The <code>stop</code> script is just a one-liner <code>os.kill(pid, signal.SIGHUP)</code>, but after that the children processes (worker processes and http server process) end nicely, but the main process just stays there, I don't know what keeps it from returning.</p>
| 4 | 2009-06-20T13:22:22Z | 1,034,694 | <p>I tried a different approach, and this seems to work (note I took out the daemon portions of the code as I didn't have that module installed).</p>
<pre><code>import signal
class Manager:
"""
This manager starts the http server processes and worker
processes, creates the input/output queues that keep the processes
work together nicely.
"""
def __init__(self):
self.NUMBER_OF_PROCESSES = cpu_count()
def start(self):
# all your code minus the loop
print "waiting to die"
signal.pause()
def stop(self):
print "quitting ..."
# all your code minus self.running
manager = Manager()
signal.signal(signal.SIGHUP, lambda signum, frame: manager.stop())
manager.start()
</code></pre>
<p>One warning, is that signal.pause() will unpause for any signal, so you may want to change your code accordingly.</p>
<p><strong>EDIT:</strong></p>
<p>The following works just fine for me:</p>
<pre><code>import daemon
import signal
import time
class Manager:
"""
This manager starts the http server processes and worker
processes, creates the input/output queues that keep the processes
work together nicely.
"""
def __init__(self):
self.NUMBER_OF_PROCESSES = 5
def start(self):
# all your code minus the loop
print "waiting to die"
self.running = 1
while self.running:
time.sleep(1)
print "quit"
def stop(self):
print "quitting ..."
# all your code minus self.running
self.running = 0
manager = Manager()
context = daemon.DaemonContext()
context.signal_map = {signal.SIGHUP : lambda signum, frame: manager.stop()}
context.open()
manager.start()
</code></pre>
<p>What version of python are you using?</p>
| 1 | 2009-06-23T19:34:59Z | [
"python",
"daemon",
"multiprocessing"
] |
Problem with exiting a daemonized process | 1,021,613 | <p>I am writing a daemon program that spawns several other children processes. After I run the <code>stop</code> script, the main process keeps running when it's intended to quit, this really confused me.</p>
<pre><code>import daemon, signal
from multiprocessing import Process, cpu_count, JoinableQueue
from http import httpserv
from worker import work
class Manager:
"""
This manager starts the http server processes and worker
processes, creates the input/output queues that keep the processes
work together nicely.
"""
def __init__(self):
self.NUMBER_OF_PROCESSES = cpu_count()
def start(self):
self.i_queue = JoinableQueue()
self.o_queue = JoinableQueue()
# Create worker processes
self.workers = [Process(target=work,
args=(self.i_queue, self.o_queue))
for i in range(self.NUMBER_OF_PROCESSES)]
for w in self.workers:
w.daemon = True
w.start()
# Create the http server process
self.http = Process(target=httpserv, args=(self.i_queue, self.o_queue))
self.http.daemon = True
self.http.start()
# Keep the current process from returning
self.running = True
while self.running:
time.sleep(1)
def stop(self):
print "quiting ..."
# Stop accepting new requests from users
os.kill(self.http.pid, signal.SIGINT)
# Waiting for all requests in output queue to be delivered
self.o_queue.join()
# Put sentinel None to input queue to signal worker processes
# to terminate
self.i_queue.put(None)
for w in self.workers:
w.join()
self.i_queue.join()
# Let main process return
self.running = False
import daemon
manager = Manager()
context = daemon.DaemonContext()
context.signal_map = {
signal.SIGHUP: lambda signum, frame: manager.stop(),
}
context.open()
manager.start()
</code></pre>
<p>The <code>stop</code> script is just a one-liner <code>os.kill(pid, signal.SIGHUP)</code>, but after that the children processes (worker processes and http server process) end nicely, but the main process just stays there, I don't know what keeps it from returning.</p>
| 4 | 2009-06-20T13:22:22Z | 1,035,672 | <p>You create the http server process but don't <code>join()</code> it. What happens if, rather than doing an <code>os.kill()</code> to stop the http server process, you send it a stop-processing sentinel (<code>None</code>, like you send to the workers) and then do a <code>self.http.join()</code>?</p>
<p><strong>Update</strong>: You also need to send the <code>None</code> sentinel to the input queue once <strong>for each worker</strong>. You could try:</p>
<pre><code> for w in self.workers:
self.i_queue.put(None)
for w in self.workers:
w.join()
</code></pre>
<p>N.B. The reason you need two loops is that if you put the <code>None</code> into the queue in the same loop that does the <code>join()</code>, that <code>None</code> may be picked up by a worker other than <code>w</code>, so joining on <code>w</code> will cause the caller to block.</p>
<p>You don't show the code for workers or http server, so I assume these are well-behaved in terms of calling task_done etc. and that each worker will quit as soon as it sees a <code>None</code>, without <code>get()</code>-ing any more things from the input queue.</p>
<p>Also, note that there is at least <a href="http://bugs.python.org/issue4660" rel="nofollow">one open, hard-to-reproduce issue</a> with <code>JoinableQueue.task_done()</code>, which may be biting you.</p>
| 1 | 2009-06-23T22:49:26Z | [
"python",
"daemon",
"multiprocessing"
] |
Probability time series, observed data probabilities (deja vu) | 1,021,704 | <p>okay folks...thanks for looking at this question. I remember doing the following below in college however I forgotten the exact solution. Any takers to steer in the right direction.</p>
<p>I have a time series of data (we'll use three) of N. The data series is sequential in order of time (e.g. obsOne[1] occurred along with obsTwo[1] and obsThree[1])</p>
<p>obsOne[47, 136, -108, -15, 22, ...], obsTwo[448, 321, 122, -207, 269, ...], obsThree[381, 283, 429, -393, 242, ...]</p>
<p>Step 2. from the data series I create a series of X range bins with width Z for each data series. (e.g. of observation obsOne: bin1 = [<-108, -108] bin2 = [-108, -26] bin3 = [-26, 55] ... binX = [136, > 136]</p>
<p>Step 3. Now create a table with all possible combinations on the data series. Thus if I had 4 bins and 3 data series all combinations would total 4x4x4 = 64 possible outcomes. (e.g. row1 = obsOne bin1 + obsTwo bin1 + obsThree bin1, row2 = obsOne bin1 + obsTwo bin1 + obsThree bin2, ... row5 = obsOne bin1 + obsTwo bin1 + obsThree binX, row6 = obsOne bin1 + obsTwo bin2 + obsThree bin1, row7 = obsOne bin1 + obsTwo bin1 + obsThree bin2, row9 = obsOne bin1 + obsTwo bin2 + obsThree binX, ...)</p>
<p>Step 4. I now go back to the data series and find where each row in the data series falls on on the table and count how many times an observation does so. (e.g. obsOne[2] obsTwo[2] obsThree[2] = row 30 on table, obsOne[X] obsTwo[X] obsThree[X] = row 52 on table. </p>
<p>Step 5. I then only take the rows on the table with positive matches, count how many observations fell on that row, dived by total number of observation in data series and that gives me my probability for that range on the observed data.</p>
<p>I apologize for this basic question, not a math expert. I have done this before many years ago. I forgot which method I used, it was much faster than this long (ancient "by hand") method. I wasn't using python at the time, it was some other proprietary package in c++. I'd like to see if something is out there that can solve this problem with python (now a python shop), could always extend, so it is soft constraint.</p>
| 1 | 2009-06-20T14:16:21Z | 1,022,285 | <p>Are you talking about something like this?</p>
<pre><code>from __future__ import division
from collections import defaultdict
obsOne= [47, 136, -108, -15, 22, ]
obsTwo= [448, 321, 122, -207, 269, ]
obsThree= [381, 283, 429, -393, 242, ]
class BinParams( object ):
def __init__( self, timeSeries, X ):
self.mx= max(timeSeries )
self.mn= min(timeSeries )
self.Z=(self.mx-self.mn)/X
def index( self, sample ):
return (sample-self.mn)//self.Z
binsOne= BinParams( obsOne, 4 )
binsTwo= BinParams( obsTwo, 4 )
binsThree= BinParams( obsThree, 4 )
counts= defaultdict(int)
for s1, s2, s3 in zip( obsOne, obsTwo, obsThree ):
posn= binsOne.index(s1), binsTwo.index(s2), binsThree.index(s3)
counts[posn] += 1
for k in counts:
print k, counts[k], counts[k]/len(counts)
</code></pre>
| 1 | 2009-06-20T19:10:47Z | [
"python",
"probability",
"time-series",
"data-analysis"
] |
Generating a 3D CAPTCHA [pic] | 1,021,721 | <p>I would like to write a Python script that would generate a 3D <a href="http://en.wikipedia.org/wiki/CAPTCHA" rel="nofollow">CAPTCHA</a> like this one:
<img src="http://i.stack.imgur.com/60KlL.png" alt="teabag captcha"></p>
<p>Which graphics libraries can I use?</p>
<p>Source: <a href="http://ocr-research.org.ua/teabag.html" rel="nofollow">ocr-research.org.ua</a></p>
| 11 | 2009-06-20T14:30:17Z | 1,021,761 | <p>I'm not sure I would bother with a full 3D library for what you have above. Just generate a matrix of 3D points, generate the text with something like PIL, scan over it to find which points on the grid are raised, pick a random camera angle and then project the points into a 2D image and draw them with PIL to the final image.</p>
<p>That being said... you may be able to use <a href="http://vpython.org" rel="nofollow">VPython</a> if you don't want to do the 3D math yourself.</p>
| 2 | 2009-06-20T14:43:12Z | [
"python",
"graphics",
"captcha"
] |
Generating a 3D CAPTCHA [pic] | 1,021,721 | <p>I would like to write a Python script that would generate a 3D <a href="http://en.wikipedia.org/wiki/CAPTCHA" rel="nofollow">CAPTCHA</a> like this one:
<img src="http://i.stack.imgur.com/60KlL.png" alt="teabag captcha"></p>
<p>Which graphics libraries can I use?</p>
<p>Source: <a href="http://ocr-research.org.ua/teabag.html" rel="nofollow">ocr-research.org.ua</a></p>
| 11 | 2009-06-20T14:30:17Z | 1,021,780 | <p>Use Python bindings for OpenGL, <a href="http://pyopengl.sourceforge.net/" rel="nofollow">http://pyopengl.sourceforge.net/</a>.</p>
<p>Create a 2D image of white color text over a black surface using <a href="http://en.wikipedia.org/wiki/Python_Imaging_Library" rel="nofollow">PIL</a>.
Make a 3D grid from this, increase z of point where color is white,
maybe set z=color value, so by blurring the image you can get real curves in the z direction.</p>
<p>Create an OpenGL triangle from these points, use wireframe mode while rendering.</p>
<p>Grab the OpenGL buffer into an image, for example,
<a href="http://python-opengl-examples.blogspot.com/2009/04/render-to-texture.html" rel="nofollow">http://python-opengl-examples.blogspot.com/2009/04/render-to-texture.html</a>.</p>
| 1 | 2009-06-20T14:51:05Z | [
"python",
"graphics",
"captcha"
] |
Generating a 3D CAPTCHA [pic] | 1,021,721 | <p>I would like to write a Python script that would generate a 3D <a href="http://en.wikipedia.org/wiki/CAPTCHA" rel="nofollow">CAPTCHA</a> like this one:
<img src="http://i.stack.imgur.com/60KlL.png" alt="teabag captcha"></p>
<p>Which graphics libraries can I use?</p>
<p>Source: <a href="http://ocr-research.org.ua/teabag.html" rel="nofollow">ocr-research.org.ua</a></p>
| 11 | 2009-06-20T14:30:17Z | 1,021,898 | <p>Another binding to consider for rendering with opengl is <a href="http://www.pyglet.org/" rel="nofollow">pyglet</a>. Its best feature is that it is just one download. I think it contains everything you need to implement what Anurag spells out.</p>
<p>I will caution you that what you're trying to do is not exactly a simple first project in 3d graphics. If this is your first exposure to OpenGL, consider a series of tutorials like <a href="http://nehe.gamedev.net/lesson.asp?index=01" rel="nofollow">NeHe Tutorials</a> and other help from the <a href="http://wwww.opengl.org/" rel="nofollow">OpenGL website</a>.</p>
| 4 | 2009-06-20T15:59:12Z | [
"python",
"graphics",
"captcha"
] |
Generating a 3D CAPTCHA [pic] | 1,021,721 | <p>I would like to write a Python script that would generate a 3D <a href="http://en.wikipedia.org/wiki/CAPTCHA" rel="nofollow">CAPTCHA</a> like this one:
<img src="http://i.stack.imgur.com/60KlL.png" alt="teabag captcha"></p>
<p>Which graphics libraries can I use?</p>
<p>Source: <a href="http://ocr-research.org.ua/teabag.html" rel="nofollow">ocr-research.org.ua</a></p>
| 11 | 2009-06-20T14:30:17Z | 1,022,263 | <p>There are many approaches. I would personally create the image in Python Imaging Library using <a href="http://www.pythonware.com/library/pil/handbook/imagedraw.htm">ImageDraw</a>'s draw.text, convert to a <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> array (usint NumPy's <a href="http://effbot.org/zone/pil-changes-116.htm">asarray</a>) then render with <a href="http://matplotlib.sourceforge.net/examples/mplot3d/wire3d_demo.html">Matplotlib</a>. (Requires Matplotlib <a href="http://sourceforge.net/project/showfiles.php?group_id=80706&package_id=82474&release_id=608756">maintenance package</a>).</p>
<p>Full code (in 2.5):</p>
<pre><code>import numpy, pylab
from PIL import Image, ImageDraw, ImageFont
import matplotlib.axes3d as axes3d
sz = (50,30)
img = Image.new('L', sz, 255)
drw = ImageDraw.Draw(img)
font = ImageFont.truetype("arial.ttf", 20)
drw.text((5,3), 'text', font=font)
img.save('c:/test.png')
X , Y = numpy.meshgrid(range(sz[0]),range(sz[1]))
Z = 1-numpy.asarray(img)/255
fig = pylab.figure()
ax = axes3d.Axes3D(fig)
ax.plot_wireframe(X, -Y, Z, rstride=1, cstride=1)
ax.set_zlim((0,50))
fig.savefig('c:/test2.png')
</code></pre>
<p><img src="http://farm3.static.flickr.com/2452/3645005748_51d9f1357e.jpg?v=0" alt="alt text"></p>
<p>Obviously there's a little work to be done, eliminating axes, changing view angle, etc..</p>
| 32 | 2009-06-20T19:04:57Z | [
"python",
"graphics",
"captcha"
] |
Can I use pywikipedia to get just the text of a page? | 1,021,884 | <p>Is it possible, using pywikipedia, to get just the text of the page, without any of the internal links or templates & without the pictures etc.?</p>
| 1 | 2009-06-20T15:49:27Z | 1,023,301 | <p>If you mean "I want to get the wikitext only", then look at the <code>wikipedia.Page</code> class, and the <code>get</code> method.</p>
<pre><code>import wikipedia
site = wikipedia.getSite('en', 'wikipedia')
page = wikipedia.Page(site, 'Test')
print page.get() # '''Test''', '''TEST''' or '''Tester''' may refer to:
#==Science and technology==
#* [[Concept inventory]] - an assessment to reveal student thinking on a topic.
# ...
</code></pre>
<p>This way you get the complete, raw wikitext from the article. </p>
<p>If you want to strip out the wiki syntax, as is transform <code>[[Concept inventory]]</code> into Concept inventory and so on, it is going to be a bit more painful.</p>
<p>The main reason for this trouble is that the MediaWiki wiki syntax has no defined grammar. Which makes it really hard to parse, and to strip. I currently know no software that allows you to do this accurately. There's the MediaWiki Parser class of course, but it's PHP, a bit hard to grasp, and its purpose is very very different.</p>
<p>But if you only want to strip out links, or very simple wiki constructs use regexes:</p>
<pre><code>text = re.sub('\[\[([^\]\|]*)\]\]', '\\1', 'Lorem ipsum [[dolor]] sit amet, consectetur adipiscing elit.')
print text #Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</code></pre>
<p>and then for piped links: </p>
<pre><code>text = re.sub('\[\[(?:[^\]\|]*)\|([^\]\|]*)\]\]', '\\1', 'Lorem ipsum [[dolor|DOLOR]] sit amet, consectetur adipiscing elit.')
print text #Lorem ipsum DOLOR sit amet, consectetur adipiscing elit.
</code></pre>
<p>and so on.</p>
<p>But for example, there is no reliable easy way to strip out nested templates from a page. And the same goes for Images that have links in their comments. It's quite hard, and involves recursively removing the most internal link and replacing it by a marker and start over. Have a look at the <code>templateWithParams</code> function in wikipedia.py if you want, but it's not pretty.</p>
| 4 | 2009-06-21T06:00:55Z | [
"python",
"wiki",
"mediawiki",
"pywikipedia"
] |
Can I use pywikipedia to get just the text of a page? | 1,021,884 | <p>Is it possible, using pywikipedia, to get just the text of the page, without any of the internal links or templates & without the pictures etc.?</p>
| 1 | 2009-06-20T15:49:27Z | 20,389,739 | <p>There is a module called <a href="https://github.com/earwig/mwparserfromhell" rel="nofollow">mwparserfromhell on Github</a> that can get you very close to what you want depending on what you need. It has a method called strip_code(), that strips a lot of the markup.</p>
<pre><code>import pywikibot
import mwparserfromhell
test_wikipedia = pywikibot.Site('en', 'test')
text = pywikibot.Page(test_wikipedia, 'Lestat_de_Lioncourt').get()
full = mwparserfromhell.parse(text)
stripped = full.strip_code()
print full
print '*******************'
print stripped
</code></pre>
<p>Comparison snippet:</p>
<pre><code>{{db-foreign}}
<!-- Commented out because image was deleted: [[Image:lestat_tom_cruise.jpg|thumb|right|[[Tom Cruise]] as Lestat in the film ''[[Interview With The Vampire: The Vampire Chronicles]]''|{{deletable image-caption|1=Friday, 11 April 2008}}]] -->
[[Image:lestat.jpg|thumb|right|[[Stuart Townsend]] as Lestat in the film ''[[Queen of the Damned (film)|Queen of the Damned]]'']]
[[Image:Lestat IWTV.jpg|thumb|right|[[Tom Cruise]] as Lestat in the 1994 film ''[[Interview with the Vampire (film)|Interview with the Vampire]]'']]
'''Lestat de Lioncourt''' is a [[fictional character]] appearing in several [[novel]]s by [[Anne Rice]], including ''[[The Vampire Lestat]]''. He is a [[vampire]] and the main character in the majority of ''[[The Vampire Chronicles]]'', narrated in first person.
==Publication history==
Lestat de Lioncourt is the narrator and main character of the majority of the novels in Anne Rice's ''The Vampire Chronicles'' series. ''[[The Vampire Lestat]]'', the second book in the series, is presented as Lestat's autobiography, and follows his exploits from his youth in France to his early years as a vampire. Many of the other books in the series are also credited as being written by Lestat.
*******************
thumb|right|Stuart Townsend as Lestat in the film ''Queen of the Damned''
'''Lestat de Lioncourt''' is a fictional character appearing in several novels by Anne Rice, including ''The Vampire Lestat''. He is a vampire and the main character in the majority of ''The Vampire Chronicles'', narrated in first person.
Publication history
Lestat de Lioncourt is the narrator and main character of the majority of the novels in Anne Rice's ''The Vampire Chronicles'' series. ''The Vampire Lestat'', the second book in the series, is presented as Lestat's autobiography, and follows his exploits from his youth in France to his early years as a vampire. Many of the other books in the series are also credited as being written by Lestat.
</code></pre>
| 0 | 2013-12-05T01:35:27Z | [
"python",
"wiki",
"mediawiki",
"pywikipedia"
] |
Checking compatibility of two python functions (or methods) | 1,022,124 | <p>Is there a possibility to check if two python functions are interchangeable? For instance, if I have</p>
<pre><code>def foo(a, b):
pass
def bar(x, y):
pass
def baz(x,y,z):
pass
</code></pre>
<p>I would like a function <code>is_compatible(a,b)</code> that returns True when passed foo and bar, but False when passed bar and baz, so I can check if they're interchangeable before actually calling either of them.</p>
| 2 | 2009-06-20T17:57:48Z | 1,022,132 | <p>Take a look at <a href="http://docs.python.org/library/inspect.html#classes-and-functions" rel="nofollow"><code>inspect.getargspec()</code></a>:</p>
<blockquote>
<h3><code>inspect.getargspec(func)</code></h3>
<p>Get the names
and default values of a functionâs
arguments. A tuple of four things is
returned: <em>(args, varargs, varkw,
defaults)</em>. args is a list of the
argument names (it may contain nested
lists). varargs and varkw are the
names of the * and ** arguments or
None. defaults is a tuple of default
argument values or None if there are
no default arguments; if this tuple
has n elements, they correspond to the
last n elements listed in args.</p>
<p><em>Changed in version 2.6: Returns a
named tuple ArgSpec(args, varargs,
keywords, defaults).</em></p>
</blockquote>
| 3 | 2009-06-20T18:02:07Z | [
"python",
"reflection"
] |
Checking compatibility of two python functions (or methods) | 1,022,124 | <p>Is there a possibility to check if two python functions are interchangeable? For instance, if I have</p>
<pre><code>def foo(a, b):
pass
def bar(x, y):
pass
def baz(x,y,z):
pass
</code></pre>
<p>I would like a function <code>is_compatible(a,b)</code> that returns True when passed foo and bar, but False when passed bar and baz, so I can check if they're interchangeable before actually calling either of them.</p>
| 2 | 2009-06-20T17:57:48Z | 1,022,133 | <p>What would you be basing the compatibility on? The number of arguments? Python has variable length argument lists, so you never know if two functions might be compatible in that sense. Data types? Python uses duck typing, so until you use an isinstance test or similar inside the function, there is no constraint on data types that a compatibility test could be based on.</p>
<p>So in short: No.</p>
<p>You should rather write good docstrings, such that any user of your API knows what the function he is giving you has to do, and then you should trust that the function you get behaves correctly. Any "compatibility" check would either rule out possibly valid functions or give you a false sense of "everything is exactly as it should be."</p>
<p>The pythonic way of exposing an API is: Write good documentation, such that people know what they need to know, and trust that they do the right thing. In critical positions you can still use <code>try: except:</code>, but anybody who is misusing your API because they just didn't care to read the doc shouldn't be given a false sense of security. And someone who did read your doc and wants to use it in a totally acceptable way should not be denied the possibility to use it on the grounds of the way they declared a function.</p>
| 4 | 2009-06-20T18:02:27Z | [
"python",
"reflection"
] |
Best way to randomize a list of strings in Python | 1,022,141 | <p>I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates - same string may appear once or more in the input and must appear the same number of times in the output.</p>
<p>I see several "brute force" ways of doing that (using loops, god forbid), one of which I'm currently using. However, knowing Python there's probably a cool one-liner do get the job done, right?</p>
| 64 | 2009-06-20T18:05:44Z | 1,022,145 | <p>Looks like this is the simplest way, if not the most truly random (<a href="https://stackoverflow.com/questions/3062741/maximal-length-of-list-to-shuffle-with-python-random-shuffle">this question</a> more fully explains the limitations): <a href="http://docs.python.org/library/random.html#random.shuffle" rel="nofollow">http://docs.python.org/library/random.html#random.shuffle</a></p>
| 13 | 2009-06-20T18:07:44Z | [
"python",
"string",
"random"
] |
Best way to randomize a list of strings in Python | 1,022,141 | <p>I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates - same string may appear once or more in the input and must appear the same number of times in the output.</p>
<p>I see several "brute force" ways of doing that (using loops, god forbid), one of which I'm currently using. However, knowing Python there's probably a cool one-liner do get the job done, right?</p>
| 64 | 2009-06-20T18:05:44Z | 1,022,151 | <pre><code>>>> import random
>>> x = [1, 2, 3, 4, 3, 4]
>>> random.shuffle(x)
>>> x
[4, 4, 3, 1, 2, 3]
>>> random.shuffle(x)
>>> x
[3, 4, 2, 1, 3, 4]
</code></pre>
| 162 | 2009-06-20T18:09:19Z | [
"python",
"string",
"random"
] |
Best way to randomize a list of strings in Python | 1,022,141 | <p>I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates - same string may appear once or more in the input and must appear the same number of times in the output.</p>
<p>I see several "brute force" ways of doing that (using loops, god forbid), one of which I'm currently using. However, knowing Python there's probably a cool one-liner do get the job done, right?</p>
| 64 | 2009-06-20T18:05:44Z | 1,022,154 | <p>You'll have to read the strings into an array and then use a shuffling algorithm. I recommend <a href="http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates%5Fshuffle" rel="nofollow">Fisher-Yates shuffle</a></p>
| 3 | 2009-06-20T18:12:13Z | [
"python",
"string",
"random"
] |
Best way to randomize a list of strings in Python | 1,022,141 | <p>I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates - same string may appear once or more in the input and must appear the same number of times in the output.</p>
<p>I see several "brute force" ways of doing that (using loops, god forbid), one of which I'm currently using. However, knowing Python there's probably a cool one-liner do get the job done, right?</p>
| 64 | 2009-06-20T18:05:44Z | 3,568,748 | <p>Given a string <em>item</em>, here is a one-liner: </p>
<pre><code>''.join([str(w) for w in random.sample(item, len(item))])
</code></pre>
| 4 | 2010-08-25T17:45:50Z | [
"python",
"string",
"random"
] |
Commenting code in Notepad++ | 1,022,261 | <p>I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.</p>
<p>Since so many language settings are supported in Notepad++, I'm curious to find a way to block comment code.</p>
| 67 | 2009-06-20T19:03:15Z | 1,022,265 | <p>Try Ctrl+K.</p>
| 18 | 2009-06-20T19:05:17Z | [
"python",
"comments",
"notepad++"
] |
Commenting code in Notepad++ | 1,022,261 | <p>I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.</p>
<p>Since so many language settings are supported in Notepad++, I'm curious to find a way to block comment code.</p>
| 67 | 2009-06-20T19:03:15Z | 1,022,270 | <p><kbd>CTRL</kbd>+<kbd>Q</kbd> Block comment/uncomment.</p>
<p>More <a href="http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Keyboard_And_Mouse_Shortcuts">Notepad++ keyboard shortcuts</a>.</p>
| 90 | 2009-06-20T19:06:48Z | [
"python",
"comments",
"notepad++"
] |
Commenting code in Notepad++ | 1,022,261 | <p>I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.</p>
<p>Since so many language settings are supported in Notepad++, I'm curious to find a way to block comment code.</p>
| 67 | 2009-06-20T19:03:15Z | 4,318,460 | <p>for .sql files <kbd>Ctrl</kbd>+<kbd>K</kbd> or <kbd>Ctrl</kbd>+<kbd>Q</kbd> does not work.</p>
<p>to insert comments in .sql files in Notepad++ try <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Q</kbd></p>
<p>(there is no shortcut to uncomment the code block though. I have tried that on v5.8.2 ) </p>
| 7 | 2010-11-30T20:49:20Z | [
"python",
"comments",
"notepad++"
] |
Commenting code in Notepad++ | 1,022,261 | <p>I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.</p>
<p>Since so many language settings are supported in Notepad++, I'm curious to find a way to block comment code.</p>
| 67 | 2009-06-20T19:03:15Z | 21,064,238 | <p>This link was exactly what I was searching for .</p>
<p>Let me summarize the answers for others' benefit (<strong>for python and notepad++</strong>)</p>
<p>1) <strong>Ctrl + K</strong> on multiple lines (i.e. selected region) allows you to <strong><em>block comment</em></strong>. </p>
<p>Also note that pressing the combination multiple times allows you to add multiple "#"s (sometimes I use that while testing to differentiate from other comments)</p>
<p>2) <strong>Ctrl + Shift + K</strong> (on the commented region) allows you to perform <strong><em>block uncomment</em></strong></p>
<p>3) <strong>Ctrl + Shift + K</strong> on an uncommented selected region <strong><em>does not comment it</em></strong></p>
<p>4) <strong>Ctrl + Q</strong> allows you to <strong>block comment/uncomment</strong> in a <strong><em>toggled mode</em></strong> (meaning, you cannot add multiple '#'s like in 1) )</p>
<p>Hope this helps another wandering soul.</p>
<p><em>Question - how would you develop a hack of keyboard combinations to comment/uncomment if there were no shortcuts? Just curious. I've no clue hence asking.</em></p>
| 9 | 2014-01-11T15:41:17Z | [
"python",
"comments",
"notepad++"
] |
Commenting code in Notepad++ | 1,022,261 | <p>I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.</p>
<p>Since so many language settings are supported in Notepad++, I'm curious to find a way to block comment code.</p>
| 67 | 2009-06-20T19:03:15Z | 25,138,274 | <p>Yes in <strong>Notepad++</strong> you can do that!</p>
<p>Some hotkeys regarding comments:</p>
<ul>
<li><kbd>Ctrl+Q</kbd> Toggle block comment</li>
<li><kbd>Ctrl+K</kbd> Block comment</li>
<li><kbd>Ctrl+Shift+K</kbd> Block uncomment</li>
<li><kbd>Ctrl+Shift+Q</kbd> Stream comment</li>
</ul>
<p>Source: <a href="http://www.shortcutworld.com/en/win/Notepad-plus-plus_5.9.html">shortcutworld.com</a> from the <strong>Comment / uncomment</strong> section.</p>
<p>On the link you will find many other useful shortcuts too.</p>
| 5 | 2014-08-05T11:58:25Z | [
"python",
"comments",
"notepad++"
] |
Commenting code in Notepad++ | 1,022,261 | <p>I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.</p>
<p>Since so many language settings are supported in Notepad++, I'm curious to find a way to block comment code.</p>
| 67 | 2009-06-20T19:03:15Z | 28,001,389 | <p>In your n++ editor, you can go to
<strong><em>Setting</em></strong> > <strong><em>Shortcut mapper</em></strong>
and find all shortcut information as well as you can edit them :)</p>
| 0 | 2015-01-17T16:07:20Z | [
"python",
"comments",
"notepad++"
] |
Commenting code in Notepad++ | 1,022,261 | <p>I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.</p>
<p>Since so many language settings are supported in Notepad++, I'm curious to find a way to block comment code.</p>
| 67 | 2009-06-20T19:03:15Z | 33,506,958 | <p>Two ways for block commenting:</p>
<ol>
<li>Ctrl+Shift+Q</li>
</ol>
<p>or </p>
<ol>
<li>Select the block</li>
<li>Alt + Right click</li>
<li>Choose block comment.</li>
</ol>
| 0 | 2015-11-03T18:56:48Z | [
"python",
"comments",
"notepad++"
] |
Commenting code in Notepad++ | 1,022,261 | <p>I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.</p>
<p>Since so many language settings are supported in Notepad++, I'm curious to find a way to block comment code.</p>
| 67 | 2009-06-20T19:03:15Z | 33,527,432 | <p>Use shortcut: Ctrl+Q.
You can customize in Settings</p>
| 0 | 2015-11-04T16:48:42Z | [
"python",
"comments",
"notepad++"
] |
Python behavior of string in loop | 1,022,264 | <p>In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks.</p>
<pre><code>s = 'these-three_words'
seperators = ('-','_')
for sep in seperators:
s = sep.join([i.capitalize() for i in s.split(sep)])
print s
print s
stdout:
These-Three_words
These-three_Words
These-three_Words
</code></pre>
| 1 | 2009-06-20T19:05:08Z | 1,022,288 | <p><a href="http://docs.python.org/library/stdtypes.html#str.capitalize" rel="nofollow"><code>capitalize</code></a> turns the first character uppercase and the rest of the string lowercase.</p>
<p>In the first iteration, it looks like this:</p>
<pre><code>>>> [i.capitalize() for i in s.split('-')]
['These', 'Three_words']
</code></pre>
<p>In the second iteration, the strings are the separated into:</p>
<pre><code>>>> [i for i in s.split('_')]
['These-Three', 'words']
</code></pre>
<p>So running capitalize on both will then turn the T in Three lowercase.</p>
| 6 | 2009-06-20T19:11:56Z | [
"python",
"string",
"loops"
] |
Python behavior of string in loop | 1,022,264 | <p>In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks.</p>
<pre><code>s = 'these-three_words'
seperators = ('-','_')
for sep in seperators:
s = sep.join([i.capitalize() for i in s.split(sep)])
print s
print s
stdout:
These-Three_words
These-three_Words
These-three_Words
</code></pre>
| 1 | 2009-06-20T19:05:08Z | 1,022,291 | <p><code>str.capitalize</code> capitalizes the first character and lowercases the remaining characters.</p>
| 2 | 2009-06-20T19:12:47Z | [
"python",
"string",
"loops"
] |
Python behavior of string in loop | 1,022,264 | <p>In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks.</p>
<pre><code>s = 'these-three_words'
seperators = ('-','_')
for sep in seperators:
s = sep.join([i.capitalize() for i in s.split(sep)])
print s
print s
stdout:
These-Three_words
These-three_Words
These-three_Words
</code></pre>
| 1 | 2009-06-20T19:05:08Z | 1,022,298 | <p>You could use <a href="http://docs.python.org/library/stdtypes.html#str.title" rel="nofollow"><code>title()</code></a>:</p>
<pre><code>>>> s = 'these-three_words'
>>> print s.title()
These-Three_Words
</code></pre>
| 5 | 2009-06-20T19:14:28Z | [
"python",
"string",
"loops"
] |
Python behavior of string in loop | 1,022,264 | <p>In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks.</p>
<pre><code>s = 'these-three_words'
seperators = ('-','_')
for sep in seperators:
s = sep.join([i.capitalize() for i in s.split(sep)])
print s
print s
stdout:
These-Three_words
These-three_Words
These-three_Words
</code></pre>
| 1 | 2009-06-20T19:05:08Z | 1,022,301 | <p>Capitalize() will return a copy of the string with <b>only its first character</b> capitalized. You could use this:</p>
<pre>
def cap(s):
return s[0].upper() + s[1:]
</pre>
| 2 | 2009-06-20T19:15:07Z | [
"python",
"string",
"loops"
] |
StringListProperty in GAE | 1,022,382 | <p>Is there any way to edit StringListProperty fields via Google's Data Viewer, or some other clever approach?</p>
<p>The last I want to do is to modify my application in such way that it provides special throwaway page for just that reason - I don't feel like it's the optimal solution.</p>
<p>Cheers,</p>
<p>MH</p>
| 1 | 2009-06-20T19:48:30Z | 1,022,444 | <p>I would recommend using the <a href="http://code.google.com/appengine/articles/remote%5Fapi.html" rel="nofollow">Remote API</a>; you can edit anything in your datastore with a minimum of fuss and no special pages needed.</p>
| 2 | 2009-06-20T20:17:27Z | [
"python",
"google-app-engine"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.