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 |
|---|---|---|---|---|---|---|---|---|---|
Why do pythonistas call the current reference "self" and not "this"? | 1,079,983 | <p>Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.</p>
<p>I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.</p>
<p>So where does this convention come from?</p>
| 35 | 2009-07-03T16:06:00Z | 1,079,995 | <p>Smalltalk, which predates Java of course.</p>
| 18 | 2009-07-03T16:09:38Z | [
"python"
] |
Why do pythonistas call the current reference "self" and not "this"? | 1,079,983 | <p>Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.</p>
<p>I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.</p>
<p>So where does this convention come from?</p>
| 35 | 2009-07-03T16:06:00Z | 1,080,001 | <p>Check the <a href="http://python-history.blogspot.com/2009/02/adding-support-for-user-defined-classes.html">history of Python</a> for user defined classes:</p>
<blockquote>
<p>Instead, one simply defines a function whose first argument corresponds to the instance, which by convention is named "self." For example:</p>
</blockquote>
<pre><code>def spam(self,y):
print self.x, y
</code></pre>
<blockquote>
<p>This approach resembles something I
had seen in Modula-3, which had
already provided me with the syntax
for import and exception handling.</p>
</blockquote>
<p>It's a choice as good as any other. You might ask why C++, Java, and C# chose "this" just as easily.</p>
| 27 | 2009-07-03T16:11:11Z | [
"python"
] |
Why do pythonistas call the current reference "self" and not "this"? | 1,079,983 | <p>Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.</p>
<p>I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.</p>
<p>So where does this convention come from?</p>
| 35 | 2009-07-03T16:06:00Z | 1,080,192 | <p>Smalltalk-80, released by Xerox in 1980, used <code>self</code>. Objective-C (early 1980s) layers Smalltalk features over C, so it uses <code>self</code> too. Modula-3 (1988), Python (late 1980s), and Ruby (mid 1990s) also follow this tradition.</p>
<p>C++, also dating from the early 1980s, chose <code>this</code> instead of <code>self</code>. Since Java was designed to be familiar to C/C++ developers, it uses <code>this</code> too.</p>
<p>Smalltalk uses the metaphor of objects sending messages to each other, so "self" just indicates that the object is sending a message to itself.</p>
| 61 | 2009-07-03T17:09:52Z | [
"python"
] |
Why do pythonistas call the current reference "self" and not "this"? | 1,079,983 | <p>Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.</p>
<p>I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.</p>
<p>So where does this convention come from?</p>
| 35 | 2009-07-03T16:06:00Z | 1,081,235 | <p>I think that since it's explicitly declared it makes more sense seeing an actual argument called "self" rather than "this". From the grammatical point of view at least, "self" is not as context dependent as "this".</p>
<p>I don't know if I made myself clear enough, but anyway this is just a subjective appreciation.</p>
| 5 | 2009-07-04T00:54:30Z | [
"python"
] |
Why do pythonistas call the current reference "self" and not "this"? | 1,079,983 | <p>Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.</p>
<p>I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.</p>
<p>So where does this convention come from?</p>
| 35 | 2009-07-03T16:06:00Z | 1,081,454 | <p>The primary inspiration was Modula-3, which Guido was introduced to at DEC: </p>
<blockquote>
<p>the Modula-3 final report was being
written there at about the same time.
What I learned there showed up in
Python's exception handling, modules,
and the fact that methods explicitly
contain âselfâ in their parameter
list.</p>
</blockquote>
<p>-- Guido, <a href="http://www.linuxjournal.com/article/2959">Linux Journal Interviews Guido van Rossum</a></p>
| 7 | 2009-07-04T03:56:41Z | [
"python"
] |
Why do pythonistas call the current reference "self" and not "this"? | 1,079,983 | <p>Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.</p>
<p>I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.</p>
<p>So where does this convention come from?</p>
| 35 | 2009-07-03T16:06:00Z | 8,620,042 | <p>With respect to python, there is nothing special about <code>self</code>. You can use <code>this</code> instead if you wanted:</p>
<p>Here's an example:</p>
<pre><code>>>> class A(object):
... def __init__(this):
... this.x = 3
...
>>> a = A()
>>> a.x
3
</code></pre>
<p>Although you could name it whatever you want, <code>self</code> is the convention for the first argument of a class function. Check out <a href="http://docs.python.org/tutorial/classes.html#random-remarks">paragraph 5 of section 9.4</a> in the python documentation, which says:</p>
<blockquote>
<p>Often, the first argument of a method is called self. This is nothing
more than a convention: the name self has absolutely no special
meaning to Python. Note, however, that by not following the convention
your code may be less readable to other Python programmers, and it is
also conceivable that a class browser program might be written that
relies upon such a convention.</p>
</blockquote>
<p>As for the convention, it started out in Smalltalk, but is also used in Object Pascal, Python, Ruby, and Objective-C. <a href="http://stackoverflow.com/a/1080192/624900">This answer</a> has a great explanation.</p>
| 14 | 2011-12-23T19:49:27Z | [
"python"
] |
Why do pythonistas call the current reference "self" and not "this"? | 1,079,983 | <p>Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.</p>
<p>I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.</p>
<p>So where does this convention come from?</p>
| 35 | 2009-07-03T16:06:00Z | 8,620,086 | <p>Python follows Smalltalk's footsteps in the aspect - self is used in Smalltalk as well. I guess the <em>real</em> question should be 'why did Bjarne decide to use <code>this</code> in C++'...</p>
| 7 | 2011-12-23T19:54:24Z | [
"python"
] |
Why do pythonistas call the current reference "self" and not "this"? | 1,079,983 | <p>Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.</p>
<p>I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.</p>
<p>So where does this convention come from?</p>
| 35 | 2009-07-03T16:06:00Z | 8,620,108 | <p><code>self</code> is not a keyword (*).</p>
<p><code>self</code> represents by convention the address of the current object</p>
<p>You can get more info on <code>self</code> <a href="http://stackoverflow.com/questions/2709821/python-self-explained">here</a>.</p>
<p>Why not <code>this</code> ? well it is a convention for a name. You can use <code>this</code> for your code if you like it better.</p>
<hr>
<p>(*) This answer has been ported and merged here from a question asking <code>why 'self' instead of 'this' keyword</code>. As the clarification in this first line could be useful for others I keep it here.</p>
| 2 | 2011-12-23T19:56:17Z | [
"python"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 1,080,053 | <p>You might try this:</p>
<pre><code>filter(lambda x: installWow(x, 'installed by me') and False, wowList)
</code></pre>
<p>That way, the return result is an empty list no matter what.</p>
<p>Or you could just drop the <code>and False</code> if you can force <code>installWow()</code> to always return <code>False</code> (or 0 or <code>None</code> or another expression that evaluates false).</p>
| 4 | 2009-07-03T16:30:22Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 1,080,054 | <p>Every expression evaluates to something, so you always get a result, whichever way you do it. And any such returned object (just like your list) will get thrown away afterwards because there's no reference to it anymore.</p>
<p>To clarify: Very few things in python are statements that don't return anything. Even a function call like</p>
<pre><code>doSomething()
</code></pre>
<p>still returns a value, even if it gets discarded right away. There is no such thing as Pascal's function / procedure distinction in python.</p>
| 6 | 2009-07-03T16:30:39Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 1,080,056 | <p>You could use a filter and a function that doesn't return a True value. You'd get an empty return list since filter only adds the values which evaluates to true, which I suppose would save you some memory. Something like this:</p>
<pre><code>#!/usr/bin/env python
y = 0
def myfunction(x):
global y
y += x
input = (1, 2, 3, 4)
print "Filter output: %s" % repr(filter(myfunction, input))
print "Side effect result: %d" % y
</code></pre>
<p>Running it produces this output:</p>
<pre><code>Filter output: ()
Side effect result: 10
</code></pre>
| 4 | 2009-07-03T16:32:07Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 1,080,100 | <p>How about this?</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
del x
</code></pre>
| 12 | 2009-07-03T16:45:26Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 1,080,269 | <p>if it is ok to distruct wowList</p>
<pre><code>while wowList: installWow(wowList.pop(), 'installed by me')
</code></pre>
<p>if you do want to maintain wowList</p>
<pre><code>wowListR = wowList[:]
while wowListR: installWow(wowListR.pop(), 'installed by me')
</code></pre>
<p>and if order matters</p>
<pre><code>wowListR = wowList[:]; wowListR.reverse()
while wowListR: installWow(wowListR.pop(), 'installed by me')
</code></pre>
<p>Though as the solution of the puzzle I like the first :)</p>
| 3 | 2009-07-03T17:32:31Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 1,080,293 | <p>I can not resist myself to post it as separate answer</p>
<pre><code>reduce(lambda x,y: x(y, 'installed by me') , wowList, installWow)
</code></pre>
<p>only twist is installWow should return itself e.g.</p>
<pre><code>def installWow(*args):
print args
return installWow
</code></pre>
| 3 | 2009-07-03T17:41:16Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 1,080,300 | <p>You could make your own "each" function:</p>
<pre>
<code>
def each(fn, items):
for item in items:
fn(item)
# called thus
each(lambda x: installWow(x, 'installed by me'), wowList)
</code>
</pre>
<p>Basically it's just map, but without the results being returned. By using a function you'll ensure that the "item" variable doesn't leak into the current scope.</p>
| 20 | 2009-07-03T17:45:30Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 1,080,336 | <p>first rewrite the for loop as a generator expression, which does not allocate any memory. </p>
<pre><code>(installWow(x, 'installed by me') for x in wowList )
</code></pre>
<p>But this expression doesn't actually do anything without finding some way to consume it. So we can rewrite this to yield something determinate, rather than rely on the possibly <code>None</code> result of <code>installWow</code>. </p>
<pre><code>( [1, installWow(x, 'installed by me')][0] for x in wowList )
</code></pre>
<p>which creates a list, but returns only the constant 1. this can be consumed conveniently with <code>reduce</code></p>
<pre><code>reduce(sum, ( [1, installWow(x, 'installed by me')][0] for x in wowList ))
</code></pre>
<p>Which conveniently returns the number of items in wowList that were affected.</p>
| 1 | 2009-07-03T18:00:03Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 1,081,326 | <p>Just make installWow return None or make the last statement be pass like so:</p>
<pre><code>
def installWow(item, phrase='installed by me'):
print phrase
pass
</code></pre>
<p>and use this:</p>
<pre><code>
list(x for x in wowList if installWow(x))
</code></pre>
<p>x won't be set in the global name space and the list returned is [] a singleton</p>
| 1 | 2009-07-04T02:06:00Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 15,772,561 | <p>I tested several different variants, and here are the results I got.</p>
<p>Python 2:</p>
<pre><code>>>> timeit.timeit('for x in xrange(100): L.append(x)', 'L = []')
14.9432640076
>>> timeit.timeit('[x for x in xrange(100) if L.append(x) and False]', 'L = []')
16.7011508942
>>> timeit.timeit('next((x for x in xrange(100) if L.append(x) and False), None)', 'L = []')
15.5235641003
>>> timeit.timeit('any(L.append(x) and False for x in xrange(100))', 'L = []')
20.9048290253
>>> timeit.timeit('filter(lambda x: L.append(x) and False, xrange(100))', 'L = []')
27.8524758816
</code></pre>
<p>Python 3:</p>
<pre><code>>>> timeit.timeit('for x in range(100): L.append(x)', 'L = []')
13.719769178002025
>>> timeit.timeit('[x for x in range(100) if L.append(x) and False]', 'L = []')
15.041426660001889
>>> timeit.timeit('next((x for x in range(100) if L.append(x) and False), None)', 'L = []')
15.448063717998593
>>> timeit.timeit('any(L.append(x) and False for x in range(100))', 'L = []')
22.087335471998813
>>> timeit.timeit('next(filter(lambda x: L.append(x) and False, range(100)), None)', 'L = []')
36.72446593800123
</code></pre>
<p>Note that the time values are not that precise (for example, the relative performance of the first three options varied from run to run). My conclusion is that you should just use a loop, it's more readable and performs at least as well as the alternatives. If you want to avoid polluting the namespace, just <code>del</code> the variable after using it.</p>
| 0 | 2013-04-02T19:21:47Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 20,845,254 | <p>If you're worried about the need to control the return value (which you need to do to use <strong>filter</strong>) and prefer a simpler solution than the <strong>reduce</strong> example above, then consider using <strong>reduce</strong> directly. Your function will need to take an additional first parameter, but you can ignore it, or use a lambda to discard it:</p>
<pre><code>reduce(lambda _x: installWow(_x, 'installed by me'), wowList, None)
</code></pre>
| 1 | 2013-12-30T18:26:45Z | [
"python",
"iteration"
] |
Is there a map without result in python? | 1,080,026 | <p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p>
<pre><code>for x in wowList:
installWow(x, 'installed by me')
</code></pre>
<p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p>
<pre><code>map(lambda x: installWow(x, 'installed by me'), wowList)
</code></pre>
<p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p>
<p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
| 15 | 2009-07-03T16:20:11Z | 37,399,250 | <p>Let me preface this by saying that it seems the original poster was more concerned about namespace clutter than anything else. In that case, you can wrap your working variables in separate function namespace and call it after declaring it, or you can simply remove them from the namespace after you've used them with the "del" builtin command. Or, if you have multiple variables to clean up, def the function with all the temp variables in it, run it, then del it.</p>
<p>Read on if the main concern is optimization:</p>
<p>Three more ways, potentially faster than others described here:</p>
<ol>
<li>For Python >= 2.7, use collections.deque((installWow(x, 'installed by me') for x in wowList),0) # saves 0 entries while iterating the entire generator, but yes, still has a byproduct of a final object along with a per-item length check internally</li>
<li>If worried about this kind of overhead, install <a href="http://matthewrocklin.com/blog/work/2014/05/01/Introducing-CyToolz" rel="nofollow">cytoolz</a>. You can use <a href="http://toolz.readthedocs.io/en/latest/api.html#toolz.itertoolz.count" rel="nofollow">count</a> which still has a byproduct of incrementing a counter but it may be a smaller number of cycles than deque's per-item check, not sure. You can use it instead of any() in the next way:</li>
<li>Replace the generator expression with itertools.imap (when installWow never returns True. Otherwise you may consider itertools.ifilter and itertools.ifilterfalse with None for the predicate): any(itertools.imap(installWow,wowList,itertools.repeat('installed by me')))</li>
</ol>
<p>But the real problem here is the fact that a function returns something and you do not want it to return anything.. So to resolve this, you have 2 options. One is to refactor your code so installWow takes in the wowList and iterates it internally. Another is rather mindblowing, but you can load the installWow() function into a compiled ast like so:</p>
<pre><code>lines,lineno=inspect.getsourcelines(func) # func here is installWow without the parens
return ast.parse(join(l[4:] for l in lines if l)) # assumes the installWow function is part of a class in a module file.. For a module-level function you would not need the l[4:]
</code></pre>
<p>You can then do the same for the outer function, and traverse the ast to find the for loop. Then in the body of the for loop, insert the instalWow() function ast's function definition body, matching up the variable names. You can then simply call <a href="http://greentreesnakes.readthedocs.io/en/latest/examples.html" rel="nofollow">exec on the ast</a> itself, and provide a namespace dictionary with the right variables filled in. To make sure your tree modifications are correct, you can check what the final source code would look like by running <a href="https://astunparse.readthedocs.io/en/latest/" rel="nofollow">astunparse</a>.</p>
<p>And if that isn't enough you can go to cython and write a .pyx file which will generate and compile a .c file into a library with python bindings. Then, at least the lost cycles won't be spent converting to and from python objects and type-checking everything repeatedly.</p>
| 0 | 2016-05-23T19:42:50Z | [
"python",
"iteration"
] |
Handling authentication and proxy servers with httplib2 | 1,080,179 | <p>I'm attempting to test interactions with a Nexus server that requires authentication for the operations I intend to use, but I also need to handle an internal proxy server.</p>
<p>Based on my (limited) understanding I can add multiple handlers to the opener. However I'm still getting a 401 response. I've checked the username and password are valid. I'm not certain if cookies are required to do this and if so how they'd be included.
Any suggestions?</p>
<pre><code>baseUrl = 'server:8070/nexus-webapp-1.3.3/service/local'
params = {"[key]":"[value]"}
data = urllib.urlencode(params)
# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password as supplied
password_mgr.add_password(None, baseUrl, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
proxy_support = urllib2.ProxyHandler({})
# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(proxy_support, handler)
urllib2.install_opener(opener)
txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
req = Request(protocol+url, data, txheaders)
handle = urlopen(req)
</code></pre>
<p>This is the resulting URLError's headers field:</p>
<pre><code>>HTTPMessage: Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=B4BD05C9582F7B27495CBB675A339724; Path=/nexus-webapp-1.3.3
WWW-Authenticate: NxBASIC realm="Sonatype Nexus Repository Manager API"
Content-Type: text/html;charset=utf-8
Content-Length: 954
Date: Fri, 03 Jul 2009 17:38:42 GMT
Connection: close
</code></pre>
<p><strong>Update</strong>
It seems Nexus implement a custom version of <a href="http://svn.sonatype.org/nexus/tags/nexus-1.3.4/nexus-clients/nexus-rest-client-java/src/main/java/org/sonatype/nexus/client/rest/HttpNxBasicHelper.java" rel="nofollow">Restlet's AuthenticationHelper</a>. Thanks to Alex I knew what to look for.</p>
| 2 | 2009-07-03T17:07:12Z | 1,080,236 | <p>Can you show the full headers of the 401 response you're getting? Maybe it's not a basic auth request, maybe it's the proxy wanting its own authentication -- it's hard to guess without seeing said headers!</p>
<p><strong>Edit</strong>: thanks for showing the headers (I reformatted them as "code" else they were unreadable).</p>
<p>As I suspected, it doesn't want "Basic", it wants some other (Nexus proprietary...?) "NxBASIC" authentication protocol -- I've never heard about it (I don't know anything about Nexus) and I imagine neither has the basic authentication handler you're using (even if NxBASIC somehow accepted plain Basic authentication, the handler, knowing only that it's a different protocol, would not offer such authentication).</p>
<p>So, first you need to research exactly what that NxBASIC thing is, and for that I suspect a SO question with the right tags might help. Then, depending on what you learn, comes the interesting issue of defining a handler for it...!-(</p>
| 3 | 2009-07-03T17:22:58Z | [
"python",
"nexus",
"httplib2"
] |
Cleaning an image to only black | 1,080,219 | <p>I have an image.</p>
<p>I would like to go over that image, pixel by pixel, and any pixel that is not black should be turned to white. How do I do this?</p>
<p>(Python).</p>
<p>Thanks!</p>
| 1 | 2009-07-03T17:17:16Z | 1,080,230 | <p>You might want to check out the following library:</p>
<p><a href="http://effbot.org/imagingbook/image.htm" rel="nofollow">http://effbot.org/imagingbook/image.htm</a></p>
<p>Especially:</p>
<pre><code>im.getpixel(xy) => value or tuple
</code></pre>
<p>and </p>
<pre><code>im.putpixel(xy, colour)
</code></pre>
| 1 | 2009-07-03T17:20:47Z | [
"python",
"image-processing",
"python-imaging-library"
] |
Cleaning an image to only black | 1,080,219 | <p>I have an image.</p>
<p>I would like to go over that image, pixel by pixel, and any pixel that is not black should be turned to white. How do I do this?</p>
<p>(Python).</p>
<p>Thanks!</p>
| 1 | 2009-07-03T17:17:16Z | 1,080,279 | <p>The most efficient way is to use the point function</p>
<pre><code>def only_black(band):
if band > 0:
return 255
return 0
result = im.convert('L').point(only_black)
</code></pre>
<p>This is what the <a href="http://effbot.org/imagingbook/image.htm" rel="nofollow">PIL documentation</a> has to say about this:</p>
<blockquote>
<p>When converting to a bilevel image
(mode "1"), the source image is first
converted to black and white.
Resulting values larger than 127 are
then set to white, and the image is
dithered. To use other thresholds, use
the point method.</p>
</blockquote>
| 6 | 2009-07-03T17:36:23Z | [
"python",
"image-processing",
"python-imaging-library"
] |
Cleaning an image to only black | 1,080,219 | <p>I have an image.</p>
<p>I would like to go over that image, pixel by pixel, and any pixel that is not black should be turned to white. How do I do this?</p>
<p>(Python).</p>
<p>Thanks!</p>
| 1 | 2009-07-03T17:17:16Z | 1,080,444 | <p>You should use the <code>point</code> function, which exists specifically for this reason.</p>
<pre><code>converter= ( (0,) + 255*(255,) ).__getitem__
def black_or_white(img):
return img.convert('L').point(converter)
</code></pre>
| 3 | 2009-07-03T18:42:59Z | [
"python",
"image-processing",
"python-imaging-library"
] |
Random list with rules | 1,080,393 | <p>I'm trying to create a list of tasks that I've read from some text files and put them into lists. I want to create a master list of what I'm going to do through the day however I've got a few rules for this. </p>
<p>One list has separate daily tasks that don't depend on the order they are completed. I call this list 'daily'. I've got another list of tasks for my projects, but these do depend on the order completed. This list is called 'projects'. I have a third list of things that must be done at the end of the day. I call it 'endofday'.</p>
<p>So here are the basic rules.</p>
<p>A list of randomized tasks where daily tasks can be performed in any order, where project tasks may be randomly inserted into the main list at any position but must stay in their original order relative to each other, and end of day tasks appended to the main list.</p>
<p>I understand how to get a random number from random.randint(), appending to lists, reading files and all that......but the logic is giving me a case of 'hurty brain'. Anyone want to take a crack at this?</p>
<p>EDIT:</p>
<p>Ok I solved it on my own, but at least asking the question got me to picture it in my head. Here's what I did.</p>
<pre><code>random.shuffle(daily)
while projects:
daily.insert(random.randint(0,len(daily)), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
<p>Thanks for the answers, I'll give ya guys some kudos anyways!</p>
<p>EDIT AGAIN:</p>
<p>Crap I just realized that's not the right answer lol</p>
<p>LAST EDIT I SWEAR:</p>
<pre><code>position = []
random.shuffle(daily)
for x in range(len(projects)):
position.append(random.randint(0,len(daily)+x))
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
<p>I LIED:</p>
<p>I just thought about what happens when position has duplicate values and lo and behold my first test returned 1,3,2,4 for my projects. I'm going to suck it up and use the answerer's solution lol</p>
<p>OR NOT:</p>
<pre><code>position = []
random.shuffle(daily)
for x in range(len(projects)):
while 1:
pos = random.randint(0,len(daily)+x)
if pos not in position: break
position.append(pos)
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
| 0 | 2009-07-03T18:23:54Z | 1,080,408 | <p>Use random.shuffle to shuffle a list</p>
<p>random.shuffle(["x", "y", "z"])</p>
| 1 | 2009-07-03T18:28:46Z | [
"python",
"random"
] |
Random list with rules | 1,080,393 | <p>I'm trying to create a list of tasks that I've read from some text files and put them into lists. I want to create a master list of what I'm going to do through the day however I've got a few rules for this. </p>
<p>One list has separate daily tasks that don't depend on the order they are completed. I call this list 'daily'. I've got another list of tasks for my projects, but these do depend on the order completed. This list is called 'projects'. I have a third list of things that must be done at the end of the day. I call it 'endofday'.</p>
<p>So here are the basic rules.</p>
<p>A list of randomized tasks where daily tasks can be performed in any order, where project tasks may be randomly inserted into the main list at any position but must stay in their original order relative to each other, and end of day tasks appended to the main list.</p>
<p>I understand how to get a random number from random.randint(), appending to lists, reading files and all that......but the logic is giving me a case of 'hurty brain'. Anyone want to take a crack at this?</p>
<p>EDIT:</p>
<p>Ok I solved it on my own, but at least asking the question got me to picture it in my head. Here's what I did.</p>
<pre><code>random.shuffle(daily)
while projects:
daily.insert(random.randint(0,len(daily)), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
<p>Thanks for the answers, I'll give ya guys some kudos anyways!</p>
<p>EDIT AGAIN:</p>
<p>Crap I just realized that's not the right answer lol</p>
<p>LAST EDIT I SWEAR:</p>
<pre><code>position = []
random.shuffle(daily)
for x in range(len(projects)):
position.append(random.randint(0,len(daily)+x))
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
<p>I LIED:</p>
<p>I just thought about what happens when position has duplicate values and lo and behold my first test returned 1,3,2,4 for my projects. I'm going to suck it up and use the answerer's solution lol</p>
<p>OR NOT:</p>
<pre><code>position = []
random.shuffle(daily)
for x in range(len(projects)):
while 1:
pos = random.randint(0,len(daily)+x)
if pos not in position: break
position.append(pos)
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
| 0 | 2009-07-03T18:23:54Z | 1,080,419 | <p>How to fetch a random element in a list using python:</p>
<pre><code>>>> import random
>>> li = ["a", "b", "c"]
>>> len = (len(li))-1
>>> ran = random.randint(0, len)
>>> ran = li[ran]
>>> ran
'b'
</code></pre>
<p>But it seems you're more curious about how to design this. If so, the python tag should probably not be there. If not, the question is probably to broad to get you any good answers code-wise.</p>
| 1 | 2009-07-03T18:33:52Z | [
"python",
"random"
] |
Random list with rules | 1,080,393 | <p>I'm trying to create a list of tasks that I've read from some text files and put them into lists. I want to create a master list of what I'm going to do through the day however I've got a few rules for this. </p>
<p>One list has separate daily tasks that don't depend on the order they are completed. I call this list 'daily'. I've got another list of tasks for my projects, but these do depend on the order completed. This list is called 'projects'. I have a third list of things that must be done at the end of the day. I call it 'endofday'.</p>
<p>So here are the basic rules.</p>
<p>A list of randomized tasks where daily tasks can be performed in any order, where project tasks may be randomly inserted into the main list at any position but must stay in their original order relative to each other, and end of day tasks appended to the main list.</p>
<p>I understand how to get a random number from random.randint(), appending to lists, reading files and all that......but the logic is giving me a case of 'hurty brain'. Anyone want to take a crack at this?</p>
<p>EDIT:</p>
<p>Ok I solved it on my own, but at least asking the question got me to picture it in my head. Here's what I did.</p>
<pre><code>random.shuffle(daily)
while projects:
daily.insert(random.randint(0,len(daily)), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
<p>Thanks for the answers, I'll give ya guys some kudos anyways!</p>
<p>EDIT AGAIN:</p>
<p>Crap I just realized that's not the right answer lol</p>
<p>LAST EDIT I SWEAR:</p>
<pre><code>position = []
random.shuffle(daily)
for x in range(len(projects)):
position.append(random.randint(0,len(daily)+x))
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
<p>I LIED:</p>
<p>I just thought about what happens when position has duplicate values and lo and behold my first test returned 1,3,2,4 for my projects. I'm going to suck it up and use the answerer's solution lol</p>
<p>OR NOT:</p>
<pre><code>position = []
random.shuffle(daily)
for x in range(len(projects)):
while 1:
pos = random.randint(0,len(daily)+x)
if pos not in position: break
position.append(pos)
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
| 0 | 2009-07-03T18:23:54Z | 1,080,422 | <p>First, copy and shuffle daily to initialize master:</p>
<pre><code>master = list(daily)
random.shuffle(master)
</code></pre>
<p>then (the interesting part!-) the alteration of master (to insert projects randomly but without order changes), and finally <code>random.shuffle(endofday); master.extend(endofday)</code>.</p>
<p>As I said the alteration part is the interesting one -- what about:</p>
<pre><code>def random_mix(seq_a, seq_b):
iters = [iter(seq_a), iter(seq_b)]
while True:
it = random.choice(iters)
try: yield it.next()
except StopIteration:
iters.remove(it)
it = iters[0]
for x in it: yield x
</code></pre>
<p>Now, the mixing step becomes just <code>master = list(random_mix(master, projects))</code></p>
<p>Performance is not ideal (lots of random numbers generated here, we could do with fewer, for example), but fine if we're talking about a few dozens or hundreds of items for example.</p>
<p>This insertion randomness is not ideal -- for that, the choice between the two sequences should not be equiprobable, but rather with probability proportional to their lengths. If that's important to you, let me know with a comment and I'll edit to fix the issue, but I wanted first to offer a simpler and more understandable version!-)</p>
<p><strong>Edit</strong>: thanks for the accept, let me complete the answer anyway with a different way of "random mixing preserving order" which does use the right probabilities -- it's only slightly more complicated because it cannot just call <code>random.choice</code>;-).</p>
<pre><code>def random_mix_rp(seq_a, seq_b):
iters = [iter(seq_a), iter(seq_b)]
lens = [len(seq_a), len(seq_b)]
while True:
r = random.randrange(sum(lens))
itindex = r < lens[0]
it = iters[itindex]
lens[itindex] -= 1
try: yield it.next()
except StopIteration:
iters.remove(it)
it = iters[0]
for x in it: yield x
</code></pre>
<p>Of course other optimization opportunities arise here -- since we're tracking the lengths anyway, we could rely on a length having gone down to zero rather than on try/except to detect that one sequence is finished and we should just exhaust the other one, etc etc. But, I wanted to show the version closest to my original one. Here's one exploiting this idea to optimize and simplify:</p>
<pre><code>def random_mix_rp1(seq_a, seq_b):
iters = [iter(seq_a), iter(seq_b)]
lens = [len(seq_a), len(seq_b)]
while all(lens):
r = random.randrange(sum(lens))
itindex = r < lens[0]
it = iters[itindex]
lens[itindex] -= 1
yield it.next()
for it in iters:
for x in it: yield x
</code></pre>
| 4 | 2009-07-03T18:36:07Z | [
"python",
"random"
] |
Random list with rules | 1,080,393 | <p>I'm trying to create a list of tasks that I've read from some text files and put them into lists. I want to create a master list of what I'm going to do through the day however I've got a few rules for this. </p>
<p>One list has separate daily tasks that don't depend on the order they are completed. I call this list 'daily'. I've got another list of tasks for my projects, but these do depend on the order completed. This list is called 'projects'. I have a third list of things that must be done at the end of the day. I call it 'endofday'.</p>
<p>So here are the basic rules.</p>
<p>A list of randomized tasks where daily tasks can be performed in any order, where project tasks may be randomly inserted into the main list at any position but must stay in their original order relative to each other, and end of day tasks appended to the main list.</p>
<p>I understand how to get a random number from random.randint(), appending to lists, reading files and all that......but the logic is giving me a case of 'hurty brain'. Anyone want to take a crack at this?</p>
<p>EDIT:</p>
<p>Ok I solved it on my own, but at least asking the question got me to picture it in my head. Here's what I did.</p>
<pre><code>random.shuffle(daily)
while projects:
daily.insert(random.randint(0,len(daily)), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
<p>Thanks for the answers, I'll give ya guys some kudos anyways!</p>
<p>EDIT AGAIN:</p>
<p>Crap I just realized that's not the right answer lol</p>
<p>LAST EDIT I SWEAR:</p>
<pre><code>position = []
random.shuffle(daily)
for x in range(len(projects)):
position.append(random.randint(0,len(daily)+x))
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
<p>I LIED:</p>
<p>I just thought about what happens when position has duplicate values and lo and behold my first test returned 1,3,2,4 for my projects. I'm going to suck it up and use the answerer's solution lol</p>
<p>OR NOT:</p>
<pre><code>position = []
random.shuffle(daily)
for x in range(len(projects)):
while 1:
pos = random.randint(0,len(daily)+x)
if pos not in position: break
position.append(pos)
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
| 0 | 2009-07-03T18:23:54Z | 1,080,440 | <ol>
<li>Combine all 3 lists into a DAG</li>
<li>Perform all possible <a href="http://en.wikipedia.org/wiki/Topological%5Fsorting" rel="nofollow">topological sorts</a>, store each sort in a list.</li>
<li>Choose one from the list at random</li>
</ol>
| 1 | 2009-07-03T18:41:21Z | [
"python",
"random"
] |
Random list with rules | 1,080,393 | <p>I'm trying to create a list of tasks that I've read from some text files and put them into lists. I want to create a master list of what I'm going to do through the day however I've got a few rules for this. </p>
<p>One list has separate daily tasks that don't depend on the order they are completed. I call this list 'daily'. I've got another list of tasks for my projects, but these do depend on the order completed. This list is called 'projects'. I have a third list of things that must be done at the end of the day. I call it 'endofday'.</p>
<p>So here are the basic rules.</p>
<p>A list of randomized tasks where daily tasks can be performed in any order, where project tasks may be randomly inserted into the main list at any position but must stay in their original order relative to each other, and end of day tasks appended to the main list.</p>
<p>I understand how to get a random number from random.randint(), appending to lists, reading files and all that......but the logic is giving me a case of 'hurty brain'. Anyone want to take a crack at this?</p>
<p>EDIT:</p>
<p>Ok I solved it on my own, but at least asking the question got me to picture it in my head. Here's what I did.</p>
<pre><code>random.shuffle(daily)
while projects:
daily.insert(random.randint(0,len(daily)), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
<p>Thanks for the answers, I'll give ya guys some kudos anyways!</p>
<p>EDIT AGAIN:</p>
<p>Crap I just realized that's not the right answer lol</p>
<p>LAST EDIT I SWEAR:</p>
<pre><code>position = []
random.shuffle(daily)
for x in range(len(projects)):
position.append(random.randint(0,len(daily)+x))
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
<p>I LIED:</p>
<p>I just thought about what happens when position has duplicate values and lo and behold my first test returned 1,3,2,4 for my projects. I'm going to suck it up and use the answerer's solution lol</p>
<p>OR NOT:</p>
<pre><code>position = []
random.shuffle(daily)
for x in range(len(projects)):
while 1:
pos = random.randint(0,len(daily)+x)
if pos not in position: break
position.append(pos)
position.sort()
while projects:
daily.insert(position.pop(0), projects.pop(0))
random.shuffle(endofday)
daily.extend(endofday)
for x in daily: print x
</code></pre>
| 0 | 2009-07-03T18:23:54Z | 1,080,460 | <p>In order for the elements of the "project" list to stay in order, you could do the following:
Say you have 4 project tasks: "a,b,c,d". Then you know there are five spots where other, randomly chosen elements can be inserted (before and after each element, including the beginning and the end), while the ordering naturally stays the same.</p>
<p>Next, you can add five times a special element (e.g. "-:-") to the daily list. When you now shuffle the daily list, these special items, corresponding to "a,b,c,d" from above, are randomly placed. Now you simply have to insert the elements of the "projects" list sequentially for each special element "-:-". And you keep the ordering, yet have a completely random list regarding the tasks from the daily list.</p>
| 1 | 2009-07-03T18:48:51Z | [
"python",
"random"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 1,080,427 | <pre><code>import urllib2
import BeautifulSoup
request = urllib2.Request("http://www.gpsbasecamp.com/national-parks")
response = urllib2.urlopen(request)
soup = BeautifulSoup.BeautifulSoup(response)
for a in soup.findAll('a'):
if 'national-park' in a['href']:
print 'found a url with national-park in the link'
</code></pre>
| 25 | 2009-07-03T18:37:53Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 1,080,472 | <p>Here's a short snippet using the SoupStrainer class in BeautifulSoup:</p>
<pre><code>import httplib2
from BeautifulSoup import BeautifulSoup, SoupStrainer
http = httplib2.Http()
status, response = http.request('http://www.nytimes.com')
for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
if link.has_attr('href'):
print link['href']
</code></pre>
<p>The BeautifulSoup documentation is actually quite good, and covers a number of typical scenarios:</p>
<p><a href="http://www.crummy.com/software/BeautifulSoup/documentation.html">http://www.crummy.com/software/BeautifulSoup/documentation.html</a></p>
<p>Edit: Note that I used the SoupStrainer class because it's a bit more efficient (memory and speed wise), if you know what you're parsing in advance.</p>
| 108 | 2009-07-03T18:53:55Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 1,081,404 | <p>just for getting the links, without B.soup and regex:</p>
<pre><code>import urllib2
url="http://www.somewhere.com"
page=urllib2.urlopen(url)
data=page.read().split("</a>")
tag="<a href=\""
endtag="\">"
for item in data:
if "<a href" in item:
try:
ind = item.index(tag)
item=item[ind+len(tag):]
end=item.index(endtag)
except: pass
else:
print item[:end]
</code></pre>
<p>for more complex operations, of course BSoup is still preferred.</p>
| 3 | 2009-07-04T03:11:21Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 1,223,008 | <p>Others have recommended BeautifulSoup, but it's much better to use <a href="http://lxml.de/index.html">lxml</a>. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.</p>
<p><a href="http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/">Ian Blicking agrees</a>.</p>
<p>There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.</p>
<p>lxml.html also supports CSS3 selectors so this sort of thing is trivial.</p>
<p><strong>An example with lxml and xpath would look like this:</strong></p>
<pre><code>import urllib
import lxml.html
connection = urllib.urlopen('http://www.nytimes.com')
dom = lxml.html.fromstring(connection.read())
for link in dom.xpath('//a/@href'): # select the url in href for all a tags(links)
print link
</code></pre>
| 38 | 2009-08-03T15:34:01Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 10,771,090 | <p>Why not use regular expressions:</p>
<pre><code>import urllib2
import re
url = "http://www.somewhere.com"
page = urllib2.urlopen(url)
page = page.read()
links = re.findall(r"<a.*?\s*href=\"(.*?)\".*?>(.*?)</a>", page)
for link in links:
print('href: %s, HTML text: %s' % (link[0], link[1]))
</code></pre>
| 0 | 2012-05-27T01:49:47Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 19,222,808 | <p>Under the hood BeautifulSoup now uses lxml. Requests, lxml & list comprehensions makes a killer combo.</p>
<pre><code>import requests
import lxml.html
dom = lxml.html.fromstring(requests.get('http://www.nytimes.com').content)
[x for x in dom.xpath('//a/@href') if '//' in x and 'nytimes.com' not in x]
</code></pre>
<p>In the list comp, the "if '//' and 'url.com' not in x" is a simple method to scrub the url list of the sites 'internal' navigation urls, etc.</p>
| 4 | 2013-10-07T10:46:27Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 21,630,012 | <p>The following code is to retrieve all the links available in a webpage using urllib2 and BeautifulSoup4</p>
<pre><code> import urllib2
from bs4 import BeautifulSoup
url = urllib2.urlopen("http://www.espncricinfo.com/").read()
soup = BeautifulSoup(url)
for line in soup.find_all('a'):
print(line.get('href'))
</code></pre>
| 6 | 2014-02-07T14:17:08Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 22,583,436 | <p>For completeness sake, the BeautifulSoup 4 version, making use of the encoding supplied by the server as well:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib2
resp = urllib2.urlopen("http://www.gpsbasecamp.com/national-parks")
soup = BeautifulSoup(resp, from_encoding=resp.info().getparam('charset'))
for link in soup.find_all('a', href=True):
print link['href']
</code></pre>
<p>or the Python 3 version:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib.request
resp = urllib.request.urlopen("http://www.gpsbasecamp.com/national-parks")
soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))
for link in soup.find_all('a', href=True):
print(link['href'])
</code></pre>
<p>and a version using the <a href="http://python-requests.org"><code>requests</code> library</a>, which as written will work in both Python 2 and 3:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
resp = requests.get("http://www.gpsbasecamp.com/national-parks")
encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None
soup = BeautifulSoup(resp.content, from_encoding=encoding)
for link in soup.find_all('a', href=True):
print(link['href'])
</code></pre>
<p>The <code>soup.find_all('a', href=True)</code> call finds all <code><a></code> elements that have an <code>href</code> attribute; elements without the attribute are skipped.</p>
<p>BeautifulSoup 3 stopped development in March 2012; new projects really should use BeautifulSoup 4, always.</p>
<p>Note that you should leave decoding the HTML from bytes <em>to BeautifulSoup</em>. You can inform BeautifulSoup of the characterset found in the HTTP response headers to assist in decoding, but this <em>can</em> be wrong and conflicting with a <code><meta></code> header info found in the HTML itself.</p>
<p>With <code>requests</code>, the <code>response.encoding</code> attribute defaults to Latin-1 if the response has a <code>text/*</code> mimetype, even if no characterset was returned. This is consistent with the HTTP RFCs but painful when used with HTML parsing, so you should ignore that attribute when no <code>charset</code> is set in the Content-Type header.</p>
| 23 | 2014-03-22T20:52:44Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 25,673,146 | <pre><code>import urllib2
from bs4 import BeautifulSoup
a=urllib2.urlopen('http://dir.yahoo.com')
code=a.read()
soup=BeautifulSoup(code)
links=soup.findAll("a")
#To get href part alone
print links[0].attrs['href']
</code></pre>
| 0 | 2014-09-04T19:00:16Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 28,076,861 | <p>This script does what your looking for, But also resolves the relative links to absolute links.</p>
<pre><code>import urllib
import lxml.html
import urlparse
def get_dom(url):
connection = urllib.urlopen(url)
return lxml.html.fromstring(connection.read())
def get_links(url):
return resolve_links((link for link in get_dom(url).xpath('//a/@href')))
def guess_root(links):
for link in links:
if link.startswith('http'):
parsed_link = urlparse.urlparse(link)
scheme = parsed_link.scheme + '://'
netloc = parsed_link.netloc
return scheme + netloc
def resolve_links(links):
root = guess_root(links)
for link in links:
if not link.startswith('http'):
link = urlparse.urljoin(root, link)
yield link
for link in get_links('http://www.google.com'):
print link
</code></pre>
| 2 | 2015-01-21T21:10:19Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 31,846,278 | <p><strong><em>To find all the links, we will in this example use the urllib2 module together
with the re.module</em></strong>
*One of the most powerful function in the re module is "re.findall()".
While re.search() is used to find the first match for a pattern, re.findall() finds <em>all</em>
the matches and returns them as a list of strings, with each string representing one match*</p>
<pre><code>import urllib2
import re
#connect to a URL
website = urllib2.urlopen(url)
#read html code
html = website.read()
#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)
print links
</code></pre>
| 3 | 2015-08-06T03:22:40Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 37,758,066 | <p>BeatifulSoup's own parser can be slow. It might be more feasible to use <strong>lxml</strong> which capable of parsing directly from a URL (with limitations).</p>
<pre class="lang-python prettyprint-override"><code>import lxml.html
doc = lxml.html.parse(url)
links = doc.xpath('//a[@href]')
for link in links:
print link.attrib['href']
</code></pre>
<p>The code above will return the links as is, and in most cases they would be relative links or absolute from the site root. Since my use case is to only extract a certain type of links, below is a version that converts the links to full URLs and which optionally accepts a glob pattern like <code>*.mp3</code>. It won't handle single and double dots in the relative paths though, but so far I didn't have the need for it.</p>
<p><strong>NOTE</strong>: Direct lxml url parsing doesn't handle loading from <code>https</code> and doesn't do redirects, so for this reason the version below is using <code>urllib2</code> + <code>lxml</code>.</p>
<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python
import sys
import urllib2
import urlparse
import lxml.html
import fnmatch
def get_host(url):
p = urlparse.urlparse(url)
return "{}://{}".format(p.scheme, p.netloc)
if __name__ == '__main__':
url = sys.argv[1]
host = get_host(url)
glob_patt = len(sys.argv) > 2 and sys.argv[2] or '*'
doc = lxml.html.parse(urllib2.urlopen(url))
links = doc.xpath('//a[@href]')
for link in links:
href = link.attrib['href']
if fnmatch.fnmatch(href, glob_patt):
if not href.startswith(('http://', 'https://' 'ftp://')):
if href.startswith('/'):
href = host + href
else:
parent_url = url.rsplit('/', 1)[0]
href = '{}/{}'.format(parent_url, href)
print href
</code></pre>
<p>The usage is as follows:</p>
<pre class="lang-text prettyprint-override"><code>getlinks.py http://stackoverflow.com/a/37758066/191246
getlinks.py http://stackoverflow.com/a/37758066/191246 "*users*"
getlinks.py http://fakedomain.mu/somepage.html "*.mp3"
</code></pre>
| 0 | 2016-06-10T22:38:00Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
retrieve links from web page using python and BeautifulSoup | 1,080,411 | <p>How can I retrieve the links of a webpage and copy the url address of the links using Python?</p>
| 70 | 2009-07-03T18:29:56Z | 38,314,240 | <p>Here's an example using @ars accepted answer and the <code>BeautifulSoup4</code>, <code>requests</code>, and <code>wget</code> modules to handle the downloads.</p>
<pre><code>import requests
import wget
import os
from bs4 import BeautifulSoup, SoupStrainer
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/eeg-mld/eeg_full/'
file_type = '.tar.gz'
response = requests.get(url)
for link in BeautifulSoup(response.content, 'html.parser', parse_only=SoupStrainer('a')):
if link.has_attr('href'):
if file_type in link['href']:
full_path = url + link['href']
wget.download(full_path)
</code></pre>
| 0 | 2016-07-11T18:58:08Z | [
"python",
"hyperlink",
"beautifulsoup"
] |
How to reload a Python module that was imported in another file? | 1,080,521 | <p>I am trying to learn how Python reloads modules, but have hit a roadblock.
Let's say I have:</p>
<p><code>dir1\file1.py</code>:</p>
<pre><code>from dir2.file2 import ClassOne
myObject = ClassOne()
</code></pre>
<p><code>dir1\dir2\file2.py</code>:</p>
<pre><code>class ClassOne():
def reload_module():
reload(file2)
</code></pre>
<p>The reload call fails to find module "file2".</p>
<p>My question is, how do I do this properly, without having to keep everything in one file?</p>
<p>A related question: When the reload does work, will myObject use the new code?</p>
<p>thank you</p>
| 2 | 2009-07-03T19:13:42Z | 1,080,534 | <pre><code> def reload_module():
import file2
reload(file2)
</code></pre>
<p>However, this will <em>not</em> per se change the type of objects you've instantiated from classes held in the previous version of file2. The Python Cookbook 2nd edition has a recipe on how to accomplish such feats, and it's far too long and complex in both code and discussion to reproduce here (I believe you can read it on google book search, or failing that the original "raw" version [before all the enhancements we did to it], at least, should still be on the activestate cookbook online site).</p>
| 3 | 2009-07-03T19:17:59Z | [
"python",
"import",
"module",
"reload"
] |
Removing the Label From Django's TextArea Widget | 1,080,650 | <p>How do I remove the label that comes attached to the TextArea I am trying to use with Django? I'm trying to find ANY information about this issue but I cannot seem to find anything relating to my problem. This is what I'm doing in my code:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea())
</code></pre>
<p>This is the HTML that it produces:</p>
<pre><code><label for="id_text">Text:</label>
<textarea id="id_text" rows="10" cols="40" name="text"></textarea>
</code></pre>
<p>That label is no good and I'd like a way to remove it. That code was produced via:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>(I removed the paragraph tags because they are irrelevant)</p>
<p>EDIT: I added the class CommentForm part for further clarification.</p>
<p>Anyone have any suggestions?</p>
| 5 | 2009-07-03T19:57:55Z | 1,080,735 | <p>This should work with the latest version (trunk) of django:</p>
<pre><code>comment = forms.CharField(label="", help_text="", widget=forms.Textarea())
</code></pre>
<p>Hope that helps!</p>
| 19 | 2009-07-03T20:30:22Z | [
"python",
"django",
"textarea",
"label",
"widget"
] |
Removing the Label From Django's TextArea Widget | 1,080,650 | <p>How do I remove the label that comes attached to the TextArea I am trying to use with Django? I'm trying to find ANY information about this issue but I cannot seem to find anything relating to my problem. This is what I'm doing in my code:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea())
</code></pre>
<p>This is the HTML that it produces:</p>
<pre><code><label for="id_text">Text:</label>
<textarea id="id_text" rows="10" cols="40" name="text"></textarea>
</code></pre>
<p>That label is no good and I'd like a way to remove it. That code was produced via:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>(I removed the paragraph tags because they are irrelevant)</p>
<p>EDIT: I added the class CommentForm part for further clarification.</p>
<p>Anyone have any suggestions?</p>
| 5 | 2009-07-03T19:57:55Z | 1,080,736 | <p>The <a href="http://docs.djangoproject.com/en/dev/ref/forms/api/#ref-forms-api-configuring-label">Django documentation on customizing labels</a> says it could be turned off with <code>auto_id</code> argument to Form constructor:</p>
<pre><code>f = ContactForm(auto_id=False)
</code></pre>
| 8 | 2009-07-03T20:30:33Z | [
"python",
"django",
"textarea",
"label",
"widget"
] |
Removing the Label From Django's TextArea Widget | 1,080,650 | <p>How do I remove the label that comes attached to the TextArea I am trying to use with Django? I'm trying to find ANY information about this issue but I cannot seem to find anything relating to my problem. This is what I'm doing in my code:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea())
</code></pre>
<p>This is the HTML that it produces:</p>
<pre><code><label for="id_text">Text:</label>
<textarea id="id_text" rows="10" cols="40" name="text"></textarea>
</code></pre>
<p>That label is no good and I'd like a way to remove it. That code was produced via:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>(I removed the paragraph tags because they are irrelevant)</p>
<p>EDIT: I added the class CommentForm part for further clarification.</p>
<p>Anyone have any suggestions?</p>
| 5 | 2009-07-03T19:57:55Z | 1,080,797 | <p>A quick-and-dirty solution would be to iterate through the form manualy (with {% for field in form %}) and handle the "problematic" field specially. You could also override the as_p/as_table methods if needed. </p>
| 0 | 2009-07-03T20:55:07Z | [
"python",
"django",
"textarea",
"label",
"widget"
] |
Removing the Label From Django's TextArea Widget | 1,080,650 | <p>How do I remove the label that comes attached to the TextArea I am trying to use with Django? I'm trying to find ANY information about this issue but I cannot seem to find anything relating to my problem. This is what I'm doing in my code:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea())
</code></pre>
<p>This is the HTML that it produces:</p>
<pre><code><label for="id_text">Text:</label>
<textarea id="id_text" rows="10" cols="40" name="text"></textarea>
</code></pre>
<p>That label is no good and I'd like a way to remove it. That code was produced via:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>(I removed the paragraph tags because they are irrelevant)</p>
<p>EDIT: I added the class CommentForm part for further clarification.</p>
<p>Anyone have any suggestions?</p>
| 5 | 2009-07-03T19:57:55Z | 25,619,766 | <p>Try this in your form:</p>
<pre><code>def __init__(self, *args, **kwargs):
self.fields['comment'].label = ''
</code></pre>
<p>But for newer versions of django i prefer Iemonad's answer</p>
| 0 | 2014-09-02T09:09:33Z | [
"python",
"django",
"textarea",
"label",
"widget"
] |
In Python, how do you change an instantiated object after a reload? | 1,080,669 | <p>Let's say you have an object that was instantiated from a class inside a module.
Now, you reload that module.
The next thing you'd like to do is make that reload affect that class.</p>
<pre><code>mymodule.py
---
class ClassChange():
def run(self):
print 'one'
myexperiment.py
---
import mymodule
from mymodule import ClassChange # why is this necessary?
myObject = ClassChange()
myObject.run()
>>> one
### later, i changed this file, so that it says print 'two'
reload(mymodule)
# trick to change myObject needed here
myObject.run()
>>> two
</code></pre>
<p>Do you have to make a new ClassChange object, copy myObject into that, and delete the old myObject? Or is there a simpler way?</p>
<p>Edit: The run() method seems like a static class style method but that was only for the sake of brevity. I'd like the run() method to operate on data inside the object, so a static module function wouldn't do...</p>
| 12 | 2009-07-03T20:03:07Z | 1,080,676 | <p>You have to make a new object. There's no way to magically update the existing objects.</p>
<p>Read the <a href="http://docs.python.org/library/functions.html#reload"><code>reload</code> builtin documentation</a> - it is very clear. Here's the last paragraph:</p>
<blockquote>
<p><em>If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances â they continue to use the old class definition. The same is true for derived classes.</em></p>
</blockquote>
<p>There are other caveats in the documentation, so you really should read it, and consider alternatives. Maybe you want to start a new question with <strong>why</strong> you want to use <code>reload</code> and ask for other ways of achieving the same thing.</p>
| 5 | 2009-07-03T20:04:49Z | [
"python",
"module",
"reload",
"python-import"
] |
In Python, how do you change an instantiated object after a reload? | 1,080,669 | <p>Let's say you have an object that was instantiated from a class inside a module.
Now, you reload that module.
The next thing you'd like to do is make that reload affect that class.</p>
<pre><code>mymodule.py
---
class ClassChange():
def run(self):
print 'one'
myexperiment.py
---
import mymodule
from mymodule import ClassChange # why is this necessary?
myObject = ClassChange()
myObject.run()
>>> one
### later, i changed this file, so that it says print 'two'
reload(mymodule)
# trick to change myObject needed here
myObject.run()
>>> two
</code></pre>
<p>Do you have to make a new ClassChange object, copy myObject into that, and delete the old myObject? Or is there a simpler way?</p>
<p>Edit: The run() method seems like a static class style method but that was only for the sake of brevity. I'd like the run() method to operate on data inside the object, so a static module function wouldn't do...</p>
| 12 | 2009-07-03T20:03:07Z | 1,080,724 | <p>The following code does what you want, but <strong>please don't use it</strong> (at least not until you're very sure you're doing the right thing), <strong>I'm posting it for explanation purposes only</strong>.</p>
<p>mymodule.py:</p>
<pre><code>class ClassChange():
@classmethod
def run(cls,instance):
print 'one',id(instance)
</code></pre>
<p>myexperiment.py:</p>
<pre><code>import mymodule
myObject = mymodule.ClassChange()
mymodule.ClassChange.run(myObject)
# change mymodule.py here
reload(mymodule)
mymodule.ClassChange.run(myObject)
</code></pre>
<p>When <strong>in your code</strong> you instanciate <code>myObject</code>, you get an instance of <code>ClassChange</code>. This instance has an <strong>instance method</strong> called <code>run</code>. The object keeps this instance method (for the reason explained by nosklo) even when reloading, because reloading only reloads the <em>class</em> <code>ClassChange</code>.</p>
<p>In <strong>my code</strong> above, <code>run</code> is a <strong>class method</strong>. Class methods are always bound to and operate on the class, not the instance (which is why their first argument is usually called <code>cls</code>, not <code>self</code>). Wenn <code>ClassChange</code> is reloaded, so is this class method.</p>
<p>You can see that I also pass the <em>instance</em> as an argument to work with the correct (same) instance of ClassChange. You can see that because the same object id is printed in both cases.</p>
| 2 | 2009-07-03T20:24:14Z | [
"python",
"module",
"reload",
"python-import"
] |
In Python, how do you change an instantiated object after a reload? | 1,080,669 | <p>Let's say you have an object that was instantiated from a class inside a module.
Now, you reload that module.
The next thing you'd like to do is make that reload affect that class.</p>
<pre><code>mymodule.py
---
class ClassChange():
def run(self):
print 'one'
myexperiment.py
---
import mymodule
from mymodule import ClassChange # why is this necessary?
myObject = ClassChange()
myObject.run()
>>> one
### later, i changed this file, so that it says print 'two'
reload(mymodule)
# trick to change myObject needed here
myObject.run()
>>> two
</code></pre>
<p>Do you have to make a new ClassChange object, copy myObject into that, and delete the old myObject? Or is there a simpler way?</p>
<p>Edit: The run() method seems like a static class style method but that was only for the sake of brevity. I'd like the run() method to operate on data inside the object, so a static module function wouldn't do...</p>
| 12 | 2009-07-03T20:03:07Z | 1,080,729 | <p>I'm not sure if this is the best way to do it, or meshes with what you want to do... but this may work for you. If you want to change the behavior of a method, for all objects of a certain type... just use a function variable. For example:</p>
<pre><code>
def default_behavior(the_object):
print "one"
def some_other_behavior(the_object):
print "two"
class Foo(object):
# Class variable: a function that has the behavior
# (Takes an instance of a Foo as argument)
behavior = default_behavior
def __init__(self):
print "Foo initialized"
def method_that_changes_behavior(self):
Foo.behavior(self)
if __name__ == "__main__":
foo = Foo()
foo.method_that_changes_behavior() # prints "one"
Foo.behavior = some_other_behavior
foo.method_that_changes_behavior() # prints "two"
# OUTPUT
# Foo initialized
# one
# two
</code></pre>
<p>You can now have a class that is responsible for reloading modules, and after reloading, setting <code>Foo.behavior</code> to something new. I tried out this code. It works fine :-).</p>
<p>Does this work for you?</p>
| 1 | 2009-07-03T20:26:21Z | [
"python",
"module",
"reload",
"python-import"
] |
In Python, how do you change an instantiated object after a reload? | 1,080,669 | <p>Let's say you have an object that was instantiated from a class inside a module.
Now, you reload that module.
The next thing you'd like to do is make that reload affect that class.</p>
<pre><code>mymodule.py
---
class ClassChange():
def run(self):
print 'one'
myexperiment.py
---
import mymodule
from mymodule import ClassChange # why is this necessary?
myObject = ClassChange()
myObject.run()
>>> one
### later, i changed this file, so that it says print 'two'
reload(mymodule)
# trick to change myObject needed here
myObject.run()
>>> two
</code></pre>
<p>Do you have to make a new ClassChange object, copy myObject into that, and delete the old myObject? Or is there a simpler way?</p>
<p>Edit: The run() method seems like a static class style method but that was only for the sake of brevity. I'd like the run() method to operate on data inside the object, so a static module function wouldn't do...</p>
| 12 | 2009-07-03T20:03:07Z | 1,080,984 | <p>To update all instances of a class, it is necessary to keep track somewhere about those instances -- typically via weak references (weak value dict is handiest and general) so the "keeping track" functionality won't stop unneeded instances from going away, of course!</p>
<p>You'd normally want to keep such a container in the class object, but, in this case, since you'll be reloading the module, getting the old class object is not trivial; it's simpler to work at module level.</p>
<p>So, let's say that an "upgradable module" needs to define, at its start, a weak value dict (and an auxiliary "next key to use" int) with, say, conventional names:</p>
<pre><code>import weakref
class _List(list): pass # a weakly-referenceable sequence
_objs = weakref.WeakValueDictionary()
_nextkey = 0
def _register(obj):
_objs[_nextkey] = List((obj, type(obj).__name__))
_nextkey += 1
</code></pre>
<p>Each class in the module must have, typically in <code>__init__</code>, a call <code>_register(self)</code> to register new instances.</p>
<p>Now the "reload function" can get the roster of all instances of all classes in this module by getting a copy of <code>_objs</code> before it reloads the module.</p>
<p>If all that's needed is to change the <em>code</em>, then life is reasonably easy:</p>
<pre><code>def reload_all(amodule):
objs = getattr(amodule, '_objs', None)
reload(amodule)
if not objs: return # not an upgraable-module, or no objects
newobjs = getattr(amodule, '_objs', None)
for obj, classname in objs.values():
newclass = getattr(amodule, classname)
obj.__class__ = newclass
if newobjs: newobjs._register(obj)
</code></pre>
<p>Alas, one typically does want to give the new class a chance to upgrade an object of the old class to itself more finely, e.g. by a suitable class method. That's not too hard either:</p>
<pre><code>def reload_all(amodule):
objs = getattr(amodule, '_objs', None)
reload(amodule)
if not objs: return # not an upgraable-module, or no objects
newobjs = getattr(amodule, '_objs', None)
for obj, classname in objs:
newclass = getattr(amodule, classname)
upgrade = getattr(newclass, '_upgrade', None)
if upgrade:
upgrade(obj)
else:
obj.__class__ = newclass
if newobjs: newobjs._register(obj)
</code></pre>
<p>For example, say the new version of class Zap has renamed an attribute from foo to bar. This could be the code of the new Zap:</p>
<pre><code>class Zap(object):
def __init__(self):
_register(self)
self.bar = 23
@classmethod
def _upgrade(cls, obj):
obj.bar = obj.foo
del obj.foo
obj.__class__ = cls
</code></pre>
<p>This is NOT all -- there's a LOT more to say on the subject -- but, it IS the gist, and the answer is WAY long enough already (and I, exhausted enough;-).</p>
| 12 | 2009-07-03T21:59:27Z | [
"python",
"module",
"reload",
"python-import"
] |
In Python, how do you change an instantiated object after a reload? | 1,080,669 | <p>Let's say you have an object that was instantiated from a class inside a module.
Now, you reload that module.
The next thing you'd like to do is make that reload affect that class.</p>
<pre><code>mymodule.py
---
class ClassChange():
def run(self):
print 'one'
myexperiment.py
---
import mymodule
from mymodule import ClassChange # why is this necessary?
myObject = ClassChange()
myObject.run()
>>> one
### later, i changed this file, so that it says print 'two'
reload(mymodule)
# trick to change myObject needed here
myObject.run()
>>> two
</code></pre>
<p>Do you have to make a new ClassChange object, copy myObject into that, and delete the old myObject? Or is there a simpler way?</p>
<p>Edit: The run() method seems like a static class style method but that was only for the sake of brevity. I'd like the run() method to operate on data inside the object, so a static module function wouldn't do...</p>
| 12 | 2009-07-03T20:03:07Z | 1,081,298 | <p>There are tricks to make what you want possible.</p>
<p>Someone already mentioned that you can have a class that keeps a list of its instances, and then changing the class of each instance to the new one upon reload.</p>
<p>However, that is not efficient. A better method is to change the old class so that it is the same as the new class.</p>
<p>Take a look at an old article I wrote which is probably the best you can do for a reload that will modify old objects.</p>
<p><a href="http://www.codexon.com/posts/a-better-python-reload" rel="nofollow">http://www.codexon.com/posts/a-better-python-reload</a></p>
| 1 | 2009-07-04T01:38:04Z | [
"python",
"module",
"reload",
"python-import"
] |
In Python, how do you change an instantiated object after a reload? | 1,080,669 | <p>Let's say you have an object that was instantiated from a class inside a module.
Now, you reload that module.
The next thing you'd like to do is make that reload affect that class.</p>
<pre><code>mymodule.py
---
class ClassChange():
def run(self):
print 'one'
myexperiment.py
---
import mymodule
from mymodule import ClassChange # why is this necessary?
myObject = ClassChange()
myObject.run()
>>> one
### later, i changed this file, so that it says print 'two'
reload(mymodule)
# trick to change myObject needed here
myObject.run()
>>> two
</code></pre>
<p>Do you have to make a new ClassChange object, copy myObject into that, and delete the old myObject? Or is there a simpler way?</p>
<p>Edit: The run() method seems like a static class style method but that was only for the sake of brevity. I'd like the run() method to operate on data inside the object, so a static module function wouldn't do...</p>
| 12 | 2009-07-03T20:03:07Z | 10,002,039 | <p>My approach to this is the following:</p>
<ol>
<li>Look through all imported modules and reload only those with a new .py file (as compared to the existing .pyc file)</li>
<li>For every function and class method that is reloaded, set old_function.__code__ = new_function.__code__. </li>
<li>For every reloaded class, use gc.get_referrers to list instances of the class and set their __class__ attribute to the new version. </li>
</ol>
<p>Advantages to this approach are:</p>
<ul>
<li>Usually no need to reload modules in any particular order</li>
<li>Usually only need to reload the modules with changed code and no more</li>
<li>Don't need to modify classes to keep track of their instances</li>
</ul>
<p>You can read about the technique (and its limitations) here:
<a href="http://luke-campagnola.blogspot.com/2010/12/easy-automated-reloading-in-python.html" rel="nofollow">http://luke-campagnola.blogspot.com/2010/12/easy-automated-reloading-in-python.html</a></p>
<p>And you can download the code here:
<a href="http://luke.campagnola.me/code/downloads/reload.py" rel="nofollow">http://luke.campagnola.me/code/downloads/reload.py</a></p>
| 4 | 2012-04-03T21:58:55Z | [
"python",
"module",
"reload",
"python-import"
] |
In Python, how do you change an instantiated object after a reload? | 1,080,669 | <p>Let's say you have an object that was instantiated from a class inside a module.
Now, you reload that module.
The next thing you'd like to do is make that reload affect that class.</p>
<pre><code>mymodule.py
---
class ClassChange():
def run(self):
print 'one'
myexperiment.py
---
import mymodule
from mymodule import ClassChange # why is this necessary?
myObject = ClassChange()
myObject.run()
>>> one
### later, i changed this file, so that it says print 'two'
reload(mymodule)
# trick to change myObject needed here
myObject.run()
>>> two
</code></pre>
<p>Do you have to make a new ClassChange object, copy myObject into that, and delete the old myObject? Or is there a simpler way?</p>
<p>Edit: The run() method seems like a static class style method but that was only for the sake of brevity. I'd like the run() method to operate on data inside the object, so a static module function wouldn't do...</p>
| 12 | 2009-07-03T20:03:07Z | 15,839,610 | <p>You have to get the new class from the fresh module and assign it back to the instance.</p>
<p>If you could trigger this operation anytime you use an instance with this mixin:</p>
<pre><code>import sys
class ObjDebug(object):
def __getattribute__(self,k):
ga=object.__getattribute__
sa=object.__setattr__
cls=ga(self,'__class__')
modname=cls.__module__
mod=__import__(modname)
del sys.modules[modname]
reload(mod)
sa(self,'__class__',getattr(mod,cls.__name__))
return ga(self,k)
</code></pre>
| 2 | 2013-04-05T17:09:14Z | [
"python",
"module",
"reload",
"python-import"
] |
screenshot an application in python, regardless of what's in front of it | 1,080,719 | <p>So I can use PIL to grab a screenshot of the desktop, and then use pywin32 to get its rectangle and crop out the part I want. However, if there's something in front of the window I want, it'll occlude the application I wanted a screenshot of. Is there any way to get what windows would say an application is currently displaying? It has that data somewhere, even when other windows are in front of it.</p>
| 4 | 2009-07-03T20:22:58Z | 1,080,733 | <p>IIRC, not in Windows pre-vista - with Aero each window has it's own buffer, but before that, you would just use your method, of getting the rectangle. I'm not sure if pywin32 has Aero support or not.</p>
| 0 | 2009-07-03T20:28:31Z | [
"python",
"windows",
"screenshot"
] |
screenshot an application in python, regardless of what's in front of it | 1,080,719 | <p>So I can use PIL to grab a screenshot of the desktop, and then use pywin32 to get its rectangle and crop out the part I want. However, if there's something in front of the window I want, it'll occlude the application I wanted a screenshot of. Is there any way to get what windows would say an application is currently displaying? It has that data somewhere, even when other windows are in front of it.</p>
| 4 | 2009-07-03T20:22:58Z | 1,080,741 | <p>If you can, try saving the order of the windows, then move your app to the front, screenshot, and move it back really quickly. Might produce a bit of annoying flicker, but it might be better than nothing.</p>
| 1 | 2009-07-03T20:33:26Z | [
"python",
"windows",
"screenshot"
] |
screenshot an application in python, regardless of what's in front of it | 1,080,719 | <p>So I can use PIL to grab a screenshot of the desktop, and then use pywin32 to get its rectangle and crop out the part I want. However, if there's something in front of the window I want, it'll occlude the application I wanted a screenshot of. Is there any way to get what windows would say an application is currently displaying? It has that data somewhere, even when other windows are in front of it.</p>
| 4 | 2009-07-03T20:22:58Z | 1,080,847 | <p>I've done the same thing by giving the application I want focus before taking the shot:</p>
<pre><code>shell=win32com.client.Dispatch("Wscript.Shell")
success = shell.AppActivate(app_name) # Returns true if focus given successfully.
</code></pre>
| 3 | 2009-07-03T21:13:01Z | [
"python",
"windows",
"screenshot"
] |
screenshot an application in python, regardless of what's in front of it | 1,080,719 | <p>So I can use PIL to grab a screenshot of the desktop, and then use pywin32 to get its rectangle and crop out the part I want. However, if there's something in front of the window I want, it'll occlude the application I wanted a screenshot of. Is there any way to get what windows would say an application is currently displaying? It has that data somewhere, even when other windows are in front of it.</p>
| 4 | 2009-07-03T20:22:58Z | 1,270,114 | <p>Maybe you can position the app offscreen, then take the screenshot, then put it back?</p>
| 1 | 2009-08-13T05:03:47Z | [
"python",
"windows",
"screenshot"
] |
screenshot an application in python, regardless of what's in front of it | 1,080,719 | <p>So I can use PIL to grab a screenshot of the desktop, and then use pywin32 to get its rectangle and crop out the part I want. However, if there's something in front of the window I want, it'll occlude the application I wanted a screenshot of. Is there any way to get what windows would say an application is currently displaying? It has that data somewhere, even when other windows are in front of it.</p>
| 4 | 2009-07-03T20:22:58Z | 3,586,035 | <p>There is a way to do this, using the <code>PrintWindow</code> function. It causes the window to redraw itself on another surface.</p>
| 2 | 2010-08-27T16:01:46Z | [
"python",
"windows",
"screenshot"
] |
screenshot an application in python, regardless of what's in front of it | 1,080,719 | <p>So I can use PIL to grab a screenshot of the desktop, and then use pywin32 to get its rectangle and crop out the part I want. However, if there's something in front of the window I want, it'll occlude the application I wanted a screenshot of. Is there any way to get what windows would say an application is currently displaying? It has that data somewhere, even when other windows are in front of it.</p>
| 4 | 2009-07-03T20:22:58Z | 24,353,857 | <p>I posted working code in the answer here: <a href="https://stackoverflow.com/questions/19695214/python-screenshot-of-inactive-window-printwindow-win32gui/24352388#24352388">Python Screenshot of inactive window</a>. It uses the <code>PrintWindow</code> function.
This is the "correct" way to copy the image of a hidden window, but that doesn't mean that it will always work. It depends on the program implementing the proper message, <code>WM_Print</code> response.</p>
<p>If you try to use <code>PrintWindow</code> it doesn't work, then your only remaining option would be to bring the window to the front before taking a <code>BitBlit</code>.</p>
| 1 | 2014-06-22T17:33:40Z | [
"python",
"windows",
"screenshot"
] |
Changes to Python since Dive into Python | 1,080,734 | <p>I've been teaching myself Python by working through <a href="http://www.diveintopython.net/">Dive Into Python</a> by Mark Pilgrim. I thoroughly recommend it, as do <a href="http://stackoverflow.com/questions/34570/what-is-the-best-quick-read-python-book-out-there/34608#34608">other Stack Overflow users</a>.</p>
<p>However, the last update to Dive Into Python was five years ago. I look forward to reading the new <a href="http://diveintopython3.net/">Dive into Python 3</a> When I make the switch to 3.x, but for now, using django means I'll stick to 2.x.</p>
<p>I'm interested to know what new features of Python I'm missing out on, if I've used Dive Into Python as my primary resource for learning the language. A couple of examples that I've come across are</p>
<ul>
<li>itertools</li>
<li>ElementTree</li>
</ul>
<p>Is there anything else I'm missing out on?</p>
<p>edit: As Bastien points out in his answer, I could just read the <a href="http://docs.python.org/whatsnew/">What's New in Python</a> pages, but sometimes it's fun to discover a useful tip on Stack Overflow rather than struggle through the complete, comprehensive answer in the official documentation.</p>
| 12 | 2009-07-03T20:28:33Z | 1,080,763 | <p>I suggest that you read the âwhat's in Python 2.x?â documents.
Some things that may have missed:</p>
<ul>
<li>New-style classes (allows standard types subtyping, properties, ...).</li>
<li>The <code>with</code> keyword, which helps allocating and releasing resources.</li>
</ul>
| 0 | 2009-07-03T20:42:06Z | [
"python"
] |
Changes to Python since Dive into Python | 1,080,734 | <p>I've been teaching myself Python by working through <a href="http://www.diveintopython.net/">Dive Into Python</a> by Mark Pilgrim. I thoroughly recommend it, as do <a href="http://stackoverflow.com/questions/34570/what-is-the-best-quick-read-python-book-out-there/34608#34608">other Stack Overflow users</a>.</p>
<p>However, the last update to Dive Into Python was five years ago. I look forward to reading the new <a href="http://diveintopython3.net/">Dive into Python 3</a> When I make the switch to 3.x, but for now, using django means I'll stick to 2.x.</p>
<p>I'm interested to know what new features of Python I'm missing out on, if I've used Dive Into Python as my primary resource for learning the language. A couple of examples that I've come across are</p>
<ul>
<li>itertools</li>
<li>ElementTree</li>
</ul>
<p>Is there anything else I'm missing out on?</p>
<p>edit: As Bastien points out in his answer, I could just read the <a href="http://docs.python.org/whatsnew/">What's New in Python</a> pages, but sometimes it's fun to discover a useful tip on Stack Overflow rather than struggle through the complete, comprehensive answer in the official documentation.</p>
| 12 | 2009-07-03T20:28:33Z | 1,081,056 | <p>Mark(author of the book) had <a href="http://www.reddit.com/r/Python/comments/8miar/im%5Fnew%5Fto%5Fpython%5Fshould%5Fi%5Fread%5Fdive%5Finto%5Fpython%5F3/c09s45y">some comments</a> on this. I've shamelessly copied the related paragraph here:<br />
"""If you choose Python 2, I can only recommend "Dive Into Python" chapters 2-7, 13-15, and 17. The rest of the book is horribly out of date."""</p>
| 6 | 2009-07-03T22:42:56Z | [
"python"
] |
Changes to Python since Dive into Python | 1,080,734 | <p>I've been teaching myself Python by working through <a href="http://www.diveintopython.net/">Dive Into Python</a> by Mark Pilgrim. I thoroughly recommend it, as do <a href="http://stackoverflow.com/questions/34570/what-is-the-best-quick-read-python-book-out-there/34608#34608">other Stack Overflow users</a>.</p>
<p>However, the last update to Dive Into Python was five years ago. I look forward to reading the new <a href="http://diveintopython3.net/">Dive into Python 3</a> When I make the switch to 3.x, but for now, using django means I'll stick to 2.x.</p>
<p>I'm interested to know what new features of Python I'm missing out on, if I've used Dive Into Python as my primary resource for learning the language. A couple of examples that I've come across are</p>
<ul>
<li>itertools</li>
<li>ElementTree</li>
</ul>
<p>Is there anything else I'm missing out on?</p>
<p>edit: As Bastien points out in his answer, I could just read the <a href="http://docs.python.org/whatsnew/">What's New in Python</a> pages, but sometimes it's fun to discover a useful tip on Stack Overflow rather than struggle through the complete, comprehensive answer in the official documentation.</p>
| 12 | 2009-07-03T20:28:33Z | 1,081,188 | <p>Here's a couple of examples of the sort of answer I was thinking of:</p>
<h3>Conditional Expressions</h3>
<p>Instead of the <a href="http://www.diveintopython.net/power_of_introspection/and_or.html#d0e9975" rel="nofollow">and-or trick</a>, 2.5 offers a new way to write <a href="http://docs.python.org/whatsnew/2.5.html?highlight=with_statement#pep-308-conditional-expressions" rel="nofollow">conditional expressions</a>.</p>
<pre><code>#and-or trick:
x = condition and 'true_value' or 'false_value'
#new in 2.5:
x = 'true_value' if condition else 'false_value'
</code></pre>
<h3>Testing for keys in dictionaries</h3>
<p>has_key() <a href="http://docs.python.org/library/stdtypes.html?highlight=has_key#dict.has_key" rel="nofollow">is deprecated</a> in favor of key in d.</p>
<pre><code>>>>d={'key':'value','key2':'value2'}
>>>'key1' in d
True
</code></pre>
| 3 | 2009-07-04T00:19:26Z | [
"python"
] |
Changes to Python since Dive into Python | 1,080,734 | <p>I've been teaching myself Python by working through <a href="http://www.diveintopython.net/">Dive Into Python</a> by Mark Pilgrim. I thoroughly recommend it, as do <a href="http://stackoverflow.com/questions/34570/what-is-the-best-quick-read-python-book-out-there/34608#34608">other Stack Overflow users</a>.</p>
<p>However, the last update to Dive Into Python was five years ago. I look forward to reading the new <a href="http://diveintopython3.net/">Dive into Python 3</a> When I make the switch to 3.x, but for now, using django means I'll stick to 2.x.</p>
<p>I'm interested to know what new features of Python I'm missing out on, if I've used Dive Into Python as my primary resource for learning the language. A couple of examples that I've come across are</p>
<ul>
<li>itertools</li>
<li>ElementTree</li>
</ul>
<p>Is there anything else I'm missing out on?</p>
<p>edit: As Bastien points out in his answer, I could just read the <a href="http://docs.python.org/whatsnew/">What's New in Python</a> pages, but sometimes it's fun to discover a useful tip on Stack Overflow rather than struggle through the complete, comprehensive answer in the official documentation.</p>
| 12 | 2009-07-03T20:28:33Z | 1,081,252 | <p>Check out <a href="http://docs.python.org/whatsnew/">What's New in Python</a>. It has all the versions in the 2.x series. Per Alex's comments, you'll want to look at all Python 2.x for x > 2.</p>
<p>Highlights for day-to-day coding:</p>
<p><em>Enumeration</em>: Instead of doing:</p>
<pre><code>for i in xrange(len(sequence)):
val = sequence[i]
pass
</code></pre>
<p>You can now more succinctly write:</p>
<pre><code>for i, val in enumerate(iterable):
pass
</code></pre>
<p>This is important because it works for non-getitemable iterables (you would otherwise have to use an incrementing index counter alongside value iteration).</p>
<p><em>Logging</em>: a sane alternative to print-based debugging, standardized in a Log4j-style library module.</p>
<p><em>Booleans</em>: True and False, added for clarity: <code>return True</code> clearer intention than <code>return 1</code>.</p>
<p><em>Generators</em>: An expressive form of lazy evaluation</p>
<pre><code>evens = (i for i in xrange(limit) if i % 2 == 0)
</code></pre>
<p><em>Extended slices</em>: Builtins support strides in slices.</p>
<pre><code>assert [1, 2, 3, 4][::2] == [1, 3]
</code></pre>
<p><em>Sets</em>: For O(1) lookup semantics, you no longer have to do:</p>
<pre><code>pseudo_set = {'foo': None, 'bar': None}
assert 'foo' in pseudo_set
</code></pre>
<p>You can now do:</p>
<pre><code>set_ = set(['foo', 'bar'])
assert 'foo' in set_
</code></pre>
<p><em>Reverse iteration</em>: <code>reversed(sequence)</code> is more readable than <code>sequence[::-1]</code>.</p>
<p><em>Subprocess</em>: Unifies all the ways you might want to invoke a subprocess -- capturing outputs, feeding input, blocking or non-blocking.</p>
<p><em>Conditional expressions</em>: There's an issue with the idiom:</p>
<pre><code>a and b or c
</code></pre>
<p>Namely, when b is falsy. <code>b if a else c</code> resolves that issue.</p>
<p><em>Context management</em>: Resource acquisition/release simplified via the <code>with</code> statement.</p>
<pre><code>with open(filename) as file:
print file.read()
# File is closed outside the `with` block.
</code></pre>
<p><em>Better string formatting</em>: Too much to describe -- see Python documentation under <code>str.format()</code>.</p>
| 9 | 2009-07-04T01:02:12Z | [
"python"
] |
Changes to Python since Dive into Python | 1,080,734 | <p>I've been teaching myself Python by working through <a href="http://www.diveintopython.net/">Dive Into Python</a> by Mark Pilgrim. I thoroughly recommend it, as do <a href="http://stackoverflow.com/questions/34570/what-is-the-best-quick-read-python-book-out-there/34608#34608">other Stack Overflow users</a>.</p>
<p>However, the last update to Dive Into Python was five years ago. I look forward to reading the new <a href="http://diveintopython3.net/">Dive into Python 3</a> When I make the switch to 3.x, but for now, using django means I'll stick to 2.x.</p>
<p>I'm interested to know what new features of Python I'm missing out on, if I've used Dive Into Python as my primary resource for learning the language. A couple of examples that I've come across are</p>
<ul>
<li>itertools</li>
<li>ElementTree</li>
</ul>
<p>Is there anything else I'm missing out on?</p>
<p>edit: As Bastien points out in his answer, I could just read the <a href="http://docs.python.org/whatsnew/">What's New in Python</a> pages, but sometimes it's fun to discover a useful tip on Stack Overflow rather than struggle through the complete, comprehensive answer in the official documentation.</p>
| 12 | 2009-07-03T20:28:33Z | 1,081,361 | <p>A few "minor" features were added in 2.4 and are pervasive in new 2.x python code: decorator (2.4) and try/except/finally clauses. Before you could not do:</p>
<pre><code>try:
do_something()
except FunkyException:
handle_exception():
finally:
clean_up()
</code></pre>
<p>Both are essentially syntactic sugar, though, since you could do the same, just with a bit more code.</p>
| 2 | 2009-07-04T02:33:06Z | [
"python"
] |
Changes to Python since Dive into Python | 1,080,734 | <p>I've been teaching myself Python by working through <a href="http://www.diveintopython.net/">Dive Into Python</a> by Mark Pilgrim. I thoroughly recommend it, as do <a href="http://stackoverflow.com/questions/34570/what-is-the-best-quick-read-python-book-out-there/34608#34608">other Stack Overflow users</a>.</p>
<p>However, the last update to Dive Into Python was five years ago. I look forward to reading the new <a href="http://diveintopython3.net/">Dive into Python 3</a> When I make the switch to 3.x, but for now, using django means I'll stick to 2.x.</p>
<p>I'm interested to know what new features of Python I'm missing out on, if I've used Dive Into Python as my primary resource for learning the language. A couple of examples that I've come across are</p>
<ul>
<li>itertools</li>
<li>ElementTree</li>
</ul>
<p>Is there anything else I'm missing out on?</p>
<p>edit: As Bastien points out in his answer, I could just read the <a href="http://docs.python.org/whatsnew/">What's New in Python</a> pages, but sometimes it's fun to discover a useful tip on Stack Overflow rather than struggle through the complete, comprehensive answer in the official documentation.</p>
| 12 | 2009-07-03T20:28:33Z | 1,081,367 | <pre><code>import antigravity
</code></pre>
<p><a href="http://imgs.xkcd.com/comics/python.png" rel="nofollow">See the documentation</a></p>
| 1 | 2009-07-04T02:36:22Z | [
"python"
] |
How Do I Remove Text From Generated Django Form? | 1,080,828 | <p>So earlier I asked a question about removing the label that Django forms have by default. That worked out great, and I removed the label. However, the text that is generated by the form is still there! I would very much like to remove the text. Here is what I mean:</p>
<pre><code><p>Text: <textarea rows="10" cols="40" name="text"></textarea></p>
</code></pre>
<p>I would like to remove the Text: part of this, as I do not want it. Again, it is generated with the form I create via:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>Here is the model I use for my form:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea())
</code></pre>
<p>EDIT: So far, I've looked at all of the documentation about the label tag and what stuff Forms generate. Apparently, this is possible to remove, it just does not tell me how. Also, I can remove the colon by adding:</p>
<pre><code>label_suffix=None
</code></pre>
<p>I have now also tried label, label_tag, label_prefix, prefix, both in the form constructor and the charField constructor. Nothing.</p>
<p>As a parameter in the constructor, but this is not enough.</p>
<p>Anyone know how to fix this one?</p>
<p>EDIT2: I have changed around how the form is done:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.Textarea()
</code></pre>
<p>It's only that now. This means the Textarea is the problem. What parameter can I pass in the textarea or to the form that will remove the aforementioned problem?</p>
| 1 | 2009-07-03T21:06:16Z | 1,080,853 | <p>Have you tried:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea(), label=None)
</code></pre>
<p>?</p>
| 1 | 2009-07-03T21:13:52Z | [
"python",
"django",
"forms",
"textarea"
] |
How Do I Remove Text From Generated Django Form? | 1,080,828 | <p>So earlier I asked a question about removing the label that Django forms have by default. That worked out great, and I removed the label. However, the text that is generated by the form is still there! I would very much like to remove the text. Here is what I mean:</p>
<pre><code><p>Text: <textarea rows="10" cols="40" name="text"></textarea></p>
</code></pre>
<p>I would like to remove the Text: part of this, as I do not want it. Again, it is generated with the form I create via:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>Here is the model I use for my form:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea())
</code></pre>
<p>EDIT: So far, I've looked at all of the documentation about the label tag and what stuff Forms generate. Apparently, this is possible to remove, it just does not tell me how. Also, I can remove the colon by adding:</p>
<pre><code>label_suffix=None
</code></pre>
<p>I have now also tried label, label_tag, label_prefix, prefix, both in the form constructor and the charField constructor. Nothing.</p>
<p>As a parameter in the constructor, but this is not enough.</p>
<p>Anyone know how to fix this one?</p>
<p>EDIT2: I have changed around how the form is done:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.Textarea()
</code></pre>
<p>It's only that now. This means the Textarea is the problem. What parameter can I pass in the textarea or to the form that will remove the aforementioned problem?</p>
| 1 | 2009-07-03T21:06:16Z | 1,080,882 | <p>Try:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea(), help_text="")
</code></pre>
| 0 | 2009-07-03T21:21:08Z | [
"python",
"django",
"forms",
"textarea"
] |
How Do I Remove Text From Generated Django Form? | 1,080,828 | <p>So earlier I asked a question about removing the label that Django forms have by default. That worked out great, and I removed the label. However, the text that is generated by the form is still there! I would very much like to remove the text. Here is what I mean:</p>
<pre><code><p>Text: <textarea rows="10" cols="40" name="text"></textarea></p>
</code></pre>
<p>I would like to remove the Text: part of this, as I do not want it. Again, it is generated with the form I create via:</p>
<pre><code>{{ form.as_p }}
</code></pre>
<p>Here is the model I use for my form:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea())
</code></pre>
<p>EDIT: So far, I've looked at all of the documentation about the label tag and what stuff Forms generate. Apparently, this is possible to remove, it just does not tell me how. Also, I can remove the colon by adding:</p>
<pre><code>label_suffix=None
</code></pre>
<p>I have now also tried label, label_tag, label_prefix, prefix, both in the form constructor and the charField constructor. Nothing.</p>
<p>As a parameter in the constructor, but this is not enough.</p>
<p>Anyone know how to fix this one?</p>
<p>EDIT2: I have changed around how the form is done:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.Textarea()
</code></pre>
<p>It's only that now. This means the Textarea is the problem. What parameter can I pass in the textarea or to the form that will remove the aforementioned problem?</p>
| 1 | 2009-07-03T21:06:16Z | 1,081,150 | <p>The answer:</p>
<pre><code>class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea(), label='')
</code></pre>
<p>Also, no auto_id in the constructor when creating the object, it should be left as:</p>
<pre><code>comment = new CommentForm()
</code></pre>
| 4 | 2009-07-03T23:49:54Z | [
"python",
"django",
"forms",
"textarea"
] |
Accessing Python Objects in a Core Dump | 1,080,832 | <p>Is there anyway to discover the python value of a PyObject* from a corefile in gdb</p>
| 2 | 2009-07-03T21:07:30Z | 1,080,869 | <p>It's lots of work, but of course it can be done, especially if you have all the symbols. Look at the header files for the specific version of Python (and compilation options in use to build it): they define PyObject as a struct which includes, first and foremost, a pointer to a type. Lots of macros are used, so you may want to run the compile of that Python from sources again, with exactly the same flags but in addition a -E to stop after preprocessing, so you can refer to the specific C code that made the bits you're seeing in the core dump.</p>
<p>A type object has, among many other things, a string (array of char) that's its name, and from it you can infer what exactly objects of that type contain -- be it content directly, or maybe some content (such as a length, i.e. number of items) and a pointer to the actual data.</p>
<p>I've done such super-advanced post-mortem debugging a couple of times (starting with VERY precise knowledge of the Python versions involved and all the prepared preprocessed sources &c) and each time it took me a day or two (were I still a freelance and charging by the hour, if I had to bid on such a task I'd say at least 20 hours -- at my not-cheap hourly rates!-).</p>
<p>IOW, it's worth it only if it's really truly the only way out of some very costly pickle. On the plus side, it WILL teach you more about Python's internals than you ever thought was there, even after memorizing every line of the sources. Good luck, you'll need some!!!</p>
| 4 | 2009-07-03T21:18:06Z | [
"python",
"python-c-api",
"postmortem-debugging"
] |
Implementing a custom Python authentication handler | 1,080,920 | <p>The answer to a <a href="http://stackoverflow.com/questions/1080179/handling-authentication-and-proxy-servers-with-httplib2">previous question</a> showed that Nexus implement a <a href="http://svn.sonatype.org/nexus/tags/nexus-1.3.4/nexus-clients/nexus-rest-client-java/src/main/java/org/sonatype/nexus/client/rest/HttpNxBasicHelper.java" rel="nofollow">custom authentication helper</a> called "NxBASIC".</p>
<p>How do I begin to implement a handler in python?</p>
<p><hr /></p>
<p>Update:</p>
<p>Implementing the handler per Alex's suggestion looks to be the right approach, but fails trying to extract the scheme and realm from the authreq.
The returned value for authreq is:</p>
<pre><code>str: NxBASIC realm="Sonatype Nexus Repository Manager API""
</code></pre>
<p>AbstractBasicAuthHandler.rx.search(authreq) is only returning a single tuple:</p>
<pre><code>tuple: ('NxBASIC', '"', 'Sonatype Nexus Repository Manager API')
</code></pre>
<p>so scheme,realm = mo.groups() fails. From my limited regex knowledge it looks like the standard regex from AbstractBasicAuthHandler should match scheme and realm, but it seems not to.</p>
<p>The regex is:</p>
<pre><code>rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
'realm=(["\'])(.*?)\\2', re.I)
</code></pre>
<p><hr /></p>
<p>Update 2:
From inspection of AbstractBasicAuthHandler, the default processing is to do:</p>
<pre><code>scheme, quote, realm = mo.groups()
</code></pre>
<p>Changing to this works. I now just need to set the password against the correct realm. Thanks Alex!</p>
| 3 | 2009-07-03T21:35:58Z | 1,084,522 | <p>If, as described, name and description are the only differences between this "NxBasic" and good old "Basic", then you could essentially copy-paste-edit some code from urllib2.py (which unfortunately doesn't expose the scheme name as easily overridable in itself), as follows (see <a href="http://svn.python.org/view/python/trunk/Lib/urllib2.py?revision=72880&view=markup" rel="nofollow">urllib2.py</a>'s online sources):</p>
<pre><code>import urllib2
class HTTPNxBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
def http_error_auth_reqed(self, authreq, host, req, headers):
# host may be an authority (without userinfo) or a URL with an
# authority
# XXX could be multiple headers
authreq = headers.get(authreq, None)
if authreq:
mo = AbstractBasicAuthHandler.rx.search(authreq)
if mo:
scheme, realm = mo.groups()
if scheme.lower() == 'nxbasic':
return self.retry_http_basic_auth(host, req, realm)
def retry_http_basic_auth(self, host, req, realm):
user, pw = self.passwd.find_user_password(realm, host)
if pw is not None:
raw = "%s:%s" % (user, pw)
auth = 'NxBasic %s' % base64.b64encode(raw).strip()
if req.headers.get(self.auth_header, None) == auth:
return None
req.add_header(self.auth_header, auth)
return self.parent.open(req)
else:
return None
</code></pre>
<p>As you can see by inspection, I've just changed two strings from "Basic" to "NxBasic" (and the lowercase equivalents) from what's in urrlib2.py (in the abstract basic auth handler superclass of the http basic auth handler class).</p>
<p>Try using this version -- and if it's still not working, at least having it be your code can help you add print/logging statements, breakpoints, etc, to better understand what's breaking and how. Best of luck! (Sorry I can't help further but I don't have any Nexus around to experiment with).</p>
| 1 | 2009-07-05T17:55:26Z | [
"python",
"restlet",
"nexus",
"httplib2"
] |
Decompile .swf file to get images in python | 1,081,183 | <p>I would like to decompile a .swf file and get all the images from it, in python.</p>
<p>Are there any libraries that do this?</p>
| 8 | 2009-07-04T00:15:11Z | 1,081,195 | <p>I don't think there are any libraries available for python, but maybe you can have an offline process to decompile swf using <a href="http://www.sothink.com/product/flashdecompiler/" rel="nofollow">sothink flash decompiler</a> Also I did not come across any decompiler so far that is 100% accurate.</p>
| 2 | 2009-07-04T00:24:59Z | [
"python",
"flash"
] |
Decompile .swf file to get images in python | 1,081,183 | <p>I would like to decompile a .swf file and get all the images from it, in python.</p>
<p>Are there any libraries that do this?</p>
| 8 | 2009-07-04T00:15:11Z | 1,081,288 | <p>There are no public swf decompiler libraries for Python.</p>
<p>Use a 3rd party program and the Python <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess module</a> to execute it.</p>
| 2 | 2009-07-04T01:28:22Z | [
"python",
"flash"
] |
Decompile .swf file to get images in python | 1,081,183 | <p>I would like to decompile a .swf file and get all the images from it, in python.</p>
<p>Are there any libraries that do this?</p>
| 8 | 2009-07-04T00:15:11Z | 1,081,290 | <p>The SWFTools distribution has a command line program, SWFExtract, that can do this. You could call that from python to do what you want:</p>
<p><a href="http://www.swftools.org/">http://www.swftools.org/</a></p>
<p><a href="http://www.swftools.org/swfextract.html">http://www.swftools.org/swfextract.html</a></p>
| 6 | 2009-07-04T01:31:22Z | [
"python",
"flash"
] |
Inheriting from instance in Python | 1,081,253 | <p>In Python, I would like to construct an instance of the Child's class directly from an instance of the Parent class. For example:</p>
<pre><code>A = Parent(x, y, z)
B = Child(A)
</code></pre>
<p>This is a hack that I thought might work:</p>
<pre><code>class Parent(object):
def __init__(self, x, y, z):
print "INITILIZING PARENT"
self.x = x
self.y = y
self.z = z
class Child(Parent):
def __new__(cls, *args, **kwds):
print "NEW'ING CHILD"
if len(args) == 1 and str(type(args[0])) == "<class '__main__.Parent'>":
new_args = []
new_args.extend([args[0].x, args[0].y, args[0].z])
print "HIJACKING"
return Child(*new_args)
print "RETURNING FROM NEW IN CHILD"
return object.__new__(cls, *args, **kwds)
</code></pre>
<p>But when I run </p>
<pre><code>B = Child(A)
</code></pre>
<p>I get:</p>
<pre><code>NEW'ING CHILD
HIJACKING
NEW'ING CHILD
RETURNING FROM NEW IN CHILD
INITILIZING PARENT
Traceback (most recent call last):
File "classes.py", line 52, in <module>
B = Child(A)
TypeError: __init__() takes exactly 4 arguments (2 given)
</code></pre>
<p>It seems the hack works just as I expected but the compiler throws a TypeError at the end. I was wondering if I could overload TypeError to make it ignore the B = Child(A) idiom but I wasn't sure how to do that. In any case, would you please give me your solutions for inheriting from instances?</p>
<p>Thanks!</p>
| 8 | 2009-07-04T01:02:45Z | 1,081,271 | <p>Once <code>__new__</code> in class <code>Child</code> returns an instance of <code>Child</code>, <code>Child.__init__</code> will be called (with the same arguments <code>__new__</code> was given) on that instance -- and apparently it just inherits <code>Parent.__init__</code>, which does not take well to being called with just one arg (the other <code>Parent</code>, <code>A</code>).</p>
<p>If there is no other way a <code>Child</code> can be made, you can define a <code>Child.__init__</code> that accepts either one arg (which it ignores) or three (in which case it calls <code>Parent.__init__</code>). But it's simpler to forego <code>__new__</code> and have all the logic in <code>Child.__init__</code>, just calling the <code>Parent.__init__</code> appropriately!</p>
<p>To make this concrete with a code example:</p>
<pre><code>class Parent(object):
def __init__(self, x, y, z):
print "INITIALIZING PARENT"
self.x = x
self.y = y
self.z = z
def __str__(self):
return "%s(%r, %r, %r)" % (self.__class__.__name__,
self.x, self.y, self.z)
class Child(Parent):
_sentinel = object()
def __init__(self, x, y=_sentinel, z=_sentinel):
print "INITIALIZING CHILD"
if y is self._sentinel and z is self._sentinel:
print "HIJACKING"
z = x.z; y = x.y; x = x.x
Parent.__init__(self, x, y, z)
print "CHILD IS DONE!"
p0 = Parent(1, 2, 3)
print p0
c1 = Child(p0)
print c1
c2 = Child(4, 5, 6)
print c2
</code></pre>
| 7 | 2009-07-04T01:11:01Z | [
"python",
"inheritance",
"instance",
"overloading"
] |
Inheriting from instance in Python | 1,081,253 | <p>In Python, I would like to construct an instance of the Child's class directly from an instance of the Parent class. For example:</p>
<pre><code>A = Parent(x, y, z)
B = Child(A)
</code></pre>
<p>This is a hack that I thought might work:</p>
<pre><code>class Parent(object):
def __init__(self, x, y, z):
print "INITILIZING PARENT"
self.x = x
self.y = y
self.z = z
class Child(Parent):
def __new__(cls, *args, **kwds):
print "NEW'ING CHILD"
if len(args) == 1 and str(type(args[0])) == "<class '__main__.Parent'>":
new_args = []
new_args.extend([args[0].x, args[0].y, args[0].z])
print "HIJACKING"
return Child(*new_args)
print "RETURNING FROM NEW IN CHILD"
return object.__new__(cls, *args, **kwds)
</code></pre>
<p>But when I run </p>
<pre><code>B = Child(A)
</code></pre>
<p>I get:</p>
<pre><code>NEW'ING CHILD
HIJACKING
NEW'ING CHILD
RETURNING FROM NEW IN CHILD
INITILIZING PARENT
Traceback (most recent call last):
File "classes.py", line 52, in <module>
B = Child(A)
TypeError: __init__() takes exactly 4 arguments (2 given)
</code></pre>
<p>It seems the hack works just as I expected but the compiler throws a TypeError at the end. I was wondering if I could overload TypeError to make it ignore the B = Child(A) idiom but I wasn't sure how to do that. In any case, would you please give me your solutions for inheriting from instances?</p>
<p>Thanks!</p>
| 8 | 2009-07-04T01:02:45Z | 1,081,280 | <p>You don't define a constructor (init) for Child, so the Parent constructor is called, expecting 4 arguments while only 2 are passed in (from new). Here's one way to accomplish what you want:</p>
<pre><code>class Child(Parent):
def __init__(self, *args, **kwargs):
if len(args) == 1 and isinstance(args[0], Parent):
Parent.__init__(self, args[0].x, args[0].y, args[0].z)
else:
# do something else
</code></pre>
| 3 | 2009-07-04T01:18:16Z | [
"python",
"inheritance",
"instance",
"overloading"
] |
Inheriting from instance in Python | 1,081,253 | <p>In Python, I would like to construct an instance of the Child's class directly from an instance of the Parent class. For example:</p>
<pre><code>A = Parent(x, y, z)
B = Child(A)
</code></pre>
<p>This is a hack that I thought might work:</p>
<pre><code>class Parent(object):
def __init__(self, x, y, z):
print "INITILIZING PARENT"
self.x = x
self.y = y
self.z = z
class Child(Parent):
def __new__(cls, *args, **kwds):
print "NEW'ING CHILD"
if len(args) == 1 and str(type(args[0])) == "<class '__main__.Parent'>":
new_args = []
new_args.extend([args[0].x, args[0].y, args[0].z])
print "HIJACKING"
return Child(*new_args)
print "RETURNING FROM NEW IN CHILD"
return object.__new__(cls, *args, **kwds)
</code></pre>
<p>But when I run </p>
<pre><code>B = Child(A)
</code></pre>
<p>I get:</p>
<pre><code>NEW'ING CHILD
HIJACKING
NEW'ING CHILD
RETURNING FROM NEW IN CHILD
INITILIZING PARENT
Traceback (most recent call last):
File "classes.py", line 52, in <module>
B = Child(A)
TypeError: __init__() takes exactly 4 arguments (2 given)
</code></pre>
<p>It seems the hack works just as I expected but the compiler throws a TypeError at the end. I was wondering if I could overload TypeError to make it ignore the B = Child(A) idiom but I wasn't sure how to do that. In any case, would you please give me your solutions for inheriting from instances?</p>
<p>Thanks!</p>
| 8 | 2009-07-04T01:02:45Z | 1,081,295 | <p>Thanks, guys, that was quick! I first read Alex's comment and I rewrote the Child's <code>__init__</code> as</p>
<pre><code>def __init__(self, *args, **kwds):
if len(args) == 1 and str(type(args[0])) == "<class '__main__.Parent'>":
new_args = [args[0].x, args[0].y, args[0].z]
super(Child, self).__init__(*new_args, **kwds)
else:
super(Child, self).__init__(*args, **kwds)
</code></pre>
<p>which is very similar to what abhinavg suggested (as I just found out). And it works. Only his and ars' line</p>
<pre><code>if len(args) == 1 and isinstance(args[0], Parent):
</code></pre>
<p>is cleaner than mine.</p>
<p>Thanks again!!</p>
| 0 | 2009-07-04T01:37:25Z | [
"python",
"inheritance",
"instance",
"overloading"
] |
Inheriting from instance in Python | 1,081,253 | <p>In Python, I would like to construct an instance of the Child's class directly from an instance of the Parent class. For example:</p>
<pre><code>A = Parent(x, y, z)
B = Child(A)
</code></pre>
<p>This is a hack that I thought might work:</p>
<pre><code>class Parent(object):
def __init__(self, x, y, z):
print "INITILIZING PARENT"
self.x = x
self.y = y
self.z = z
class Child(Parent):
def __new__(cls, *args, **kwds):
print "NEW'ING CHILD"
if len(args) == 1 and str(type(args[0])) == "<class '__main__.Parent'>":
new_args = []
new_args.extend([args[0].x, args[0].y, args[0].z])
print "HIJACKING"
return Child(*new_args)
print "RETURNING FROM NEW IN CHILD"
return object.__new__(cls, *args, **kwds)
</code></pre>
<p>But when I run </p>
<pre><code>B = Child(A)
</code></pre>
<p>I get:</p>
<pre><code>NEW'ING CHILD
HIJACKING
NEW'ING CHILD
RETURNING FROM NEW IN CHILD
INITILIZING PARENT
Traceback (most recent call last):
File "classes.py", line 52, in <module>
B = Child(A)
TypeError: __init__() takes exactly 4 arguments (2 given)
</code></pre>
<p>It seems the hack works just as I expected but the compiler throws a TypeError at the end. I was wondering if I could overload TypeError to make it ignore the B = Child(A) idiom but I wasn't sure how to do that. In any case, would you please give me your solutions for inheriting from instances?</p>
<p>Thanks!</p>
| 8 | 2009-07-04T01:02:45Z | 1,081,925 | <p>OK, so I didn't realize that you where happy with a static copy of the arguments until I was already halfway done with my solution. But I decided not to waste it, so here it is anyway. The difference from the other solutions is that it will actually get the attributes from the parent even if they updated.</p>
<pre><code>_marker = object()
class Parent(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Child(Parent):
_inherited = ['x', 'y', 'z']
def __init__(self, parent):
self._parent = parent
self.a = "not got from dad"
def __getattr__(self, name, default=_marker):
if name in self._inherited:
# Get it from papa:
try:
return getattr(self._parent, name)
except AttributeError:
if default is _marker:
raise
return default
if name not in self.__dict__:
raise AttributeError(name)
return self.__dict__[name]
</code></pre>
<p>Now if we do this:</p>
<pre><code>>>> A = Parent('gotten', 'from', 'dad')
>>> B = Child(A)
>>> print "a, b and c is", B.x, B.y, B.z
a, b and c is gotten from dad
>>> print "But x is", B.a
But x is not got from dad
>>> A.x = "updated!"
>>> print "And the child also gets", B.x
And the child also gets updated!
>>> print B.doesnotexist
Traceback (most recent call last):
File "acq.py", line 44, in <module>
print B.doesnotexist
File "acq.py", line 32, in __getattr__
raise AttributeError(name)
AttributeError: doesnotexist
</code></pre>
<p>For a more generic version of this, look at the <a href="http://pypi.python.org/pypi/Acquisition" rel="nofollow">http://pypi.python.org/pypi/Acquisition</a> package. It is in fact, in some cases a bloody need solution.</p>
| 3 | 2009-07-04T10:12:09Z | [
"python",
"inheritance",
"instance",
"overloading"
] |
Inheriting from instance in Python | 1,081,253 | <p>In Python, I would like to construct an instance of the Child's class directly from an instance of the Parent class. For example:</p>
<pre><code>A = Parent(x, y, z)
B = Child(A)
</code></pre>
<p>This is a hack that I thought might work:</p>
<pre><code>class Parent(object):
def __init__(self, x, y, z):
print "INITILIZING PARENT"
self.x = x
self.y = y
self.z = z
class Child(Parent):
def __new__(cls, *args, **kwds):
print "NEW'ING CHILD"
if len(args) == 1 and str(type(args[0])) == "<class '__main__.Parent'>":
new_args = []
new_args.extend([args[0].x, args[0].y, args[0].z])
print "HIJACKING"
return Child(*new_args)
print "RETURNING FROM NEW IN CHILD"
return object.__new__(cls, *args, **kwds)
</code></pre>
<p>But when I run </p>
<pre><code>B = Child(A)
</code></pre>
<p>I get:</p>
<pre><code>NEW'ING CHILD
HIJACKING
NEW'ING CHILD
RETURNING FROM NEW IN CHILD
INITILIZING PARENT
Traceback (most recent call last):
File "classes.py", line 52, in <module>
B = Child(A)
TypeError: __init__() takes exactly 4 arguments (2 given)
</code></pre>
<p>It seems the hack works just as I expected but the compiler throws a TypeError at the end. I was wondering if I could overload TypeError to make it ignore the B = Child(A) idiom but I wasn't sure how to do that. In any case, would you please give me your solutions for inheriting from instances?</p>
<p>Thanks!</p>
| 8 | 2009-07-04T01:02:45Z | 11,974,673 | <p>I know this is an extremely old thread, but I recently ran into the same challenge as Alexandra, and this was the most relavent topic I could find. I had a parent class with many, many attributes, and I wanted to essentially 'patch' an instance of it, by keeping all of its methods and attributes, adding a few, and modifying/overwriting others. A simple subclass wouldn't work because the attributes would be filled in by the user during runtime, and I couldn't just inherit the default values from the parent class. After a lot of tinkering I found a very clean (though rather hacky) way to do it by using <code>__new__</code>. Here's an example:</p>
<pre><code>class Parent(object):
def __init__(self):
# whatever you want here
self.x = 42
self.y = 5
def f(self):
print "Parent class, x,y =", self.x, self.y
class Child(Parent):
def __new__(cls, parentInst):
parentInst.__class__ = Child
return parentInst
def __init__(self, parentInst):
# You don't call the Parent's init method here
self.y = 10
def f(self):
print "Child class, x,y =", self.x, self.y
c = Parent()
c.f() # Parent class, x,y = 42 5
c.x = 13
c.f() # Parent class, x,y = 13 5
c = Child(c)
c.f() # Child class, x,y = 13 10
</code></pre>
<p>The only special part is changing the <code>__class__</code> attribute of the Parent class in the Child's constructor. Because of this, the Child's <code>__init__</code> method will be called as usual, and to my knowledge the Child class should function exactly as any other inherited class.</p>
| 1 | 2012-08-15T18:09:21Z | [
"python",
"inheritance",
"instance",
"overloading"
] |
Inheriting from instance in Python | 1,081,253 | <p>In Python, I would like to construct an instance of the Child's class directly from an instance of the Parent class. For example:</p>
<pre><code>A = Parent(x, y, z)
B = Child(A)
</code></pre>
<p>This is a hack that I thought might work:</p>
<pre><code>class Parent(object):
def __init__(self, x, y, z):
print "INITILIZING PARENT"
self.x = x
self.y = y
self.z = z
class Child(Parent):
def __new__(cls, *args, **kwds):
print "NEW'ING CHILD"
if len(args) == 1 and str(type(args[0])) == "<class '__main__.Parent'>":
new_args = []
new_args.extend([args[0].x, args[0].y, args[0].z])
print "HIJACKING"
return Child(*new_args)
print "RETURNING FROM NEW IN CHILD"
return object.__new__(cls, *args, **kwds)
</code></pre>
<p>But when I run </p>
<pre><code>B = Child(A)
</code></pre>
<p>I get:</p>
<pre><code>NEW'ING CHILD
HIJACKING
NEW'ING CHILD
RETURNING FROM NEW IN CHILD
INITILIZING PARENT
Traceback (most recent call last):
File "classes.py", line 52, in <module>
B = Child(A)
TypeError: __init__() takes exactly 4 arguments (2 given)
</code></pre>
<p>It seems the hack works just as I expected but the compiler throws a TypeError at the end. I was wondering if I could overload TypeError to make it ignore the B = Child(A) idiom but I wasn't sure how to do that. In any case, would you please give me your solutions for inheriting from instances?</p>
<p>Thanks!</p>
| 8 | 2009-07-04T01:02:45Z | 14,182,553 | <p>I find this (encapsulation) to be the cleanest way:</p>
<pre><code>class Child(object):
def __init__(self):
self.obj = Parent()
def __getattr__(self, attr):
return getattr(self.obj, attr)
</code></pre>
<p>This way you can use all Parent's method and your own without running into the problems of inheritance.</p>
| 1 | 2013-01-06T13:22:56Z | [
"python",
"inheritance",
"instance",
"overloading"
] |
How do you do something after you render the view? (Django) | 1,081,340 | <p>I want to do something after I have rendered the view using </p>
<pre><code>return render_to_response()
</code></pre>
<p>Are signals the only way to do this? Do I need to write a custom signal or does request_finished give me enough information? Basically I need to know what page was rendered, and then do an action in response to that.</p>
<p>Thanks.</p>
<p>UPDATE FROM COMMENTS: I don't want to hold up the rendering of the page, so I want to render the page first and then do the action.</p>
| 6 | 2009-07-04T02:16:36Z | 1,081,352 | <p>In render to response, you pass the html page that you want displayed. That other page needs to send a post (via Javascript or something) that triggers the correct function in your views, then that view calls the correct next page to be shown.</p>
| -1 | 2009-07-04T02:28:08Z | [
"python",
"django"
] |
How do you do something after you render the view? (Django) | 1,081,340 | <p>I want to do something after I have rendered the view using </p>
<pre><code>return render_to_response()
</code></pre>
<p>Are signals the only way to do this? Do I need to write a custom signal or does request_finished give me enough information? Basically I need to know what page was rendered, and then do an action in response to that.</p>
<p>Thanks.</p>
<p>UPDATE FROM COMMENTS: I don't want to hold up the rendering of the page, so I want to render the page first and then do the action.</p>
| 6 | 2009-07-04T02:16:36Z | 1,081,376 | <p>If you have a long-running process, you have two simple choices.</p>
<ol>
<li><p>Spawn a subprocess prior to sending the response page.</p></li>
<li><p>Create a "background service daemon" and pass work requests to it.</p></li>
</ol>
<p>This is all outside Django. You use <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> or some other IPC method to communicate with the other process.</p>
| 3 | 2009-07-04T02:41:31Z | [
"python",
"django"
] |
How do you do something after you render the view? (Django) | 1,081,340 | <p>I want to do something after I have rendered the view using </p>
<pre><code>return render_to_response()
</code></pre>
<p>Are signals the only way to do this? Do I need to write a custom signal or does request_finished give me enough information? Basically I need to know what page was rendered, and then do an action in response to that.</p>
<p>Thanks.</p>
<p>UPDATE FROM COMMENTS: I don't want to hold up the rendering of the page, so I want to render the page first and then do the action.</p>
| 6 | 2009-07-04T02:16:36Z | 1,081,441 | <p>A common way to do this is to use message queues. You place a message on the queue, and worker threads (or processes, etc.) consume the queue and do the work after your view has completed.</p>
<p>Google App Engine has the task queue api <a href="http://code.google.com/appengine/docs/python/taskqueue/" rel="nofollow">http://code.google.com/appengine/docs/python/taskqueue/</a>, amazon has the Simple Queue Service <a href="http://aws.amazon.com/sqs/" rel="nofollow">http://aws.amazon.com/sqs/</a>. </p>
<p>A quick search didn't turn up any django pluggables that look like accepted standards. </p>
<p>A quick and dirty way to emulate the functionality is to place the 'message' in a database table, and have a cron job periodically check the table to perform the work.</p>
| 4 | 2009-07-04T03:44:31Z | [
"python",
"django"
] |
How do you do something after you render the view? (Django) | 1,081,340 | <p>I want to do something after I have rendered the view using </p>
<pre><code>return render_to_response()
</code></pre>
<p>Are signals the only way to do this? Do I need to write a custom signal or does request_finished give me enough information? Basically I need to know what page was rendered, and then do an action in response to that.</p>
<p>Thanks.</p>
<p>UPDATE FROM COMMENTS: I don't want to hold up the rendering of the page, so I want to render the page first and then do the action.</p>
| 6 | 2009-07-04T02:16:36Z | 1,081,766 | <p>Django's HttpResponse object accepts an iterator in its constructor:</p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/request-response/#passing-iterators" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/request-response/#passing-iterators</a></p>
<p>So you could do something like:</p>
<pre><code>def myiter():
yield "my content"
enqueue_some_task()
return
def myview(request):
return HttpResponse(myiter())
</code></pre>
<p>The normal use of an iterator is to send large data without reading it all into memory. For example, read chunks from a file and yield appropriately. I've never used it in this way, but it seems like it should work.</p>
| 4 | 2009-07-04T07:57:28Z | [
"python",
"django"
] |
How do you do something after you render the view? (Django) | 1,081,340 | <p>I want to do something after I have rendered the view using </p>
<pre><code>return render_to_response()
</code></pre>
<p>Are signals the only way to do this? Do I need to write a custom signal or does request_finished give me enough information? Basically I need to know what page was rendered, and then do an action in response to that.</p>
<p>Thanks.</p>
<p>UPDATE FROM COMMENTS: I don't want to hold up the rendering of the page, so I want to render the page first and then do the action.</p>
| 6 | 2009-07-04T02:16:36Z | 1,081,935 | <p>My favourite solution: A separate process that handles background tasks, typically things like indexing and sending notification mails etc. And then, during the view rendering, you send an event to the event handling system (I don't know if Django has one built in, but you always need one anyway so you should have one) and the even system then puts a message in a message queue (which is trivial to write unless you have multiple machines or multiple background processes) that does the task in question.</p>
| 2 | 2009-07-04T10:16:44Z | [
"python",
"django"
] |
How do you do something after you render the view? (Django) | 1,081,340 | <p>I want to do something after I have rendered the view using </p>
<pre><code>return render_to_response()
</code></pre>
<p>Are signals the only way to do this? Do I need to write a custom signal or does request_finished give me enough information? Basically I need to know what page was rendered, and then do an action in response to that.</p>
<p>Thanks.</p>
<p>UPDATE FROM COMMENTS: I don't want to hold up the rendering of the page, so I want to render the page first and then do the action.</p>
| 6 | 2009-07-04T02:16:36Z | 1,082,785 | <p>You spawn a separate thread and have it do the action.</p>
<pre><code>t = threading.Thread(target=do_my_action, args=[my_argument])
# We want the program to wait on this thread before shutting down.
t.setDaemon(False)
t.start()
</code></pre>
<p>This will cause 'do_my_action(my_argument)' to be executed in a second thread which will keep working even after you send your Django response and terminate the initial thread. For example it could send an email without delaying the response.</p>
| 6 | 2009-07-04T18:55:11Z | [
"python",
"django"
] |
How do you do something after you render the view? (Django) | 1,081,340 | <p>I want to do something after I have rendered the view using </p>
<pre><code>return render_to_response()
</code></pre>
<p>Are signals the only way to do this? Do I need to write a custom signal or does request_finished give me enough information? Basically I need to know what page was rendered, and then do an action in response to that.</p>
<p>Thanks.</p>
<p>UPDATE FROM COMMENTS: I don't want to hold up the rendering of the page, so I want to render the page first and then do the action.</p>
| 6 | 2009-07-04T02:16:36Z | 1,082,905 | <p>Perhaps I do not understand your question. But why not something simple like:</p>
<pre><code>try:
return render_to_response()
finally:
do_what_needs_to_be_done()
</code></pre>
| 0 | 2009-07-04T20:16:58Z | [
"python",
"django"
] |
How can I report the API of a class programmatically? | 1,081,392 | <p>My goal is to parse a class and return a data-structure (object, dictionary, etc) that is descriptive of the methods and the related parameters contained within the class. Bonus points for types and returns...</p>
<p>Requirements: Must be Python</p>
<p>For example, the below class:</p>
<pre><code>class Foo:
def bar(hello=None):
return hello
def baz(world=None):
return baz
</code></pre>
<p>Would be parsed to return</p>
<pre><code>result = {class:"Foo",
methods: [{name: "bar", params:["hello"]},
{name: "baz", params:["world"]}]}
</code></pre>
<p>So that's just an example of what I'm thinking... I'm really flexible on the data-structure.</p>
<p>Any ideas/examples on how to achieve this?</p>
| 4 | 2009-07-04T02:59:38Z | 1,081,395 | <p>You probably want to check out Python's <a href="http://docs.python.org/library/inspect.html#inspect.getmembers" rel="nofollow">inspect</a> module. It will get you most of the way there:</p>
<pre><code>>>> class Foo:
... def bar(hello=None):
... return hello
... def baz(world=None):
... return baz
...
>>> import inspect
>>> members = inspect.getmembers(Foo)
>>> print members
[('__doc__', None), ('__module__', '__main__'), ('bar', <unbound method Foo.bar>
), ('baz', <unbound method Foo.baz>)]
>>> inspect.getargspec(members[2][1])
(['hello'], None, None, (None,))
>>> inspect.getargspec(members[3][1])
(['world'], None, None, (None,))
</code></pre>
<p>This isn't in the syntax you wanted, but that part should be fairly straight forward as you read the docs.</p>
| 8 | 2009-07-04T03:03:39Z | [
"python",
"api"
] |
python tab completion in windows | 1,081,405 | <p>I'm writing a cross-platform shell like program in python and I'd like to add custom tab-completion actions. On Unix systems I can use the built-in readline module and use code like the following to specify a list of possible completions when I hit the TAB key:</p>
<pre><code>import readline
readline.parse_and_bind( 'tab: complete' )
readline.set_completer( ... )
</code></pre>
<p>How can I do this on Windows? I'd like to avoid relying on 3rd-party packages if possible. If no solution exists is it possible to simply trap TAB key press so that I can implement my own from scratch?</p>
| 5 | 2009-07-04T03:11:37Z | 1,081,416 | <p>Do u have a look at <a href="http://ipython.scipy.org/moin/PyReadline/Intro" rel="nofollow">PyReadline: a ctypes-based readline for Windows</a>? Although 3rd-party packages is NOT your option, maybe it's useful for build one's own, isn't it:).</p>
| 2 | 2009-07-04T03:19:09Z | [
"python",
"windows",
"readline",
"tab-completion"
] |
python tab completion in windows | 1,081,405 | <p>I'm writing a cross-platform shell like program in python and I'd like to add custom tab-completion actions. On Unix systems I can use the built-in readline module and use code like the following to specify a list of possible completions when I hit the TAB key:</p>
<pre><code>import readline
readline.parse_and_bind( 'tab: complete' )
readline.set_completer( ... )
</code></pre>
<p>How can I do this on Windows? I'd like to avoid relying on 3rd-party packages if possible. If no solution exists is it possible to simply trap TAB key press so that I can implement my own from scratch?</p>
| 5 | 2009-07-04T03:11:37Z | 1,081,586 | <p>you could look at how <a href="http://ipython.scipy.org/" rel="nofollow">ipython</a> does it with pyreadline as well, maybe </p>
| 0 | 2009-07-04T05:36:22Z | [
"python",
"windows",
"readline",
"tab-completion"
] |
python tab completion in windows | 1,081,405 | <p>I'm writing a cross-platform shell like program in python and I'd like to add custom tab-completion actions. On Unix systems I can use the built-in readline module and use code like the following to specify a list of possible completions when I hit the TAB key:</p>
<pre><code>import readline
readline.parse_and_bind( 'tab: complete' )
readline.set_completer( ... )
</code></pre>
<p>How can I do this on Windows? I'd like to avoid relying on 3rd-party packages if possible. If no solution exists is it possible to simply trap TAB key press so that I can implement my own from scratch?</p>
| 5 | 2009-07-04T03:11:37Z | 1,255,975 | <p>Another possibility to check out is <a href="http://newcenturycomputers.net/projects/readline.html" rel="nofollow">readline.py</a>.</p>
| 0 | 2009-08-10T16:51:00Z | [
"python",
"windows",
"readline",
"tab-completion"
] |
Python: How to set breakpoints on mac with IDLE debugger? | 1,081,536 | <p>I have access to both a PC and a mac for a python class. I find I am unable to set breakpoints in the IDLE debugger in the mac (works fine on the PC). </p>
<p>I've tried "ctrl-click" and configuring the touchpad to recognize two taps at once as a secondary click. I don't have a mouse for the mac, just the touchpad.</p>
<p>MAC OS 10.4.10 tiger </p>
<p>Python/IDLE version 2.6.1</p>
<p>I have tried STFW unsuccessfully...</p>
| 2 | 2009-07-04T05:00:20Z | 1,081,590 | <p>Have a look at the <a href="http://docs.python.org/library/pdb.html" rel="nofollow">pdb</a> module. I have just barely learned about it, and played with it a bit. It appears to enable command line debugging by allowing you to set traces within the code. This gives you interactive access to your variables and code while it is running. Not quite the same as running the IDLE debugger with breakpoints, but it may work for you. <br>See <a href="http://docs.python.org/library/pdb.html" rel="nofollow">this</a> or <a href="http://www.ferg.org/papers/debugging%5Fin%5Fpython.html" rel="nofollow">this</a> for more details. <br><br>
Something else to look at ... under Options -> Configure IDLE -> Keys, there may be a way to map keystrokes to the action of setting a breakpoint.</p>
| 1 | 2009-07-04T05:39:01Z | [
"python",
"osx",
"python-idle"
] |
Python: How to set breakpoints on mac with IDLE debugger? | 1,081,536 | <p>I have access to both a PC and a mac for a python class. I find I am unable to set breakpoints in the IDLE debugger in the mac (works fine on the PC). </p>
<p>I've tried "ctrl-click" and configuring the touchpad to recognize two taps at once as a secondary click. I don't have a mouse for the mac, just the touchpad.</p>
<p>MAC OS 10.4.10 tiger </p>
<p>Python/IDLE version 2.6.1</p>
<p>I have tried STFW unsuccessfully...</p>
| 2 | 2009-07-04T05:00:20Z | 1,110,542 | <p>If you put the following two lines:</p>
<pre><code>import pdb
pdb.set_trace()
</code></pre>
<p>Python will import the <strong>P</strong>ython <strong>D</strong>e <strong>B</strong>ugger and you will be in the interactive interpreter at this point in the code. It will evaluate all your Python expressions normally.</p>
<p>The most important commands are:</p>
<ol>
<li>s - step (forward one command)</li>
<li>c - continue (done)</li>
</ol>
<p>For a full list, see this:
<a href="http://infohost.nmt.edu/tcc/help/pubs/python22/pdb-commands.html" rel="nofollow">http://infohost.nmt.edu/tcc/help/pubs/python22/pdb-commands.html</a></p>
| 3 | 2009-07-10T16:21:09Z | [
"python",
"osx",
"python-idle"
] |
Python: How to set breakpoints on mac with IDLE debugger? | 1,081,536 | <p>I have access to both a PC and a mac for a python class. I find I am unable to set breakpoints in the IDLE debugger in the mac (works fine on the PC). </p>
<p>I've tried "ctrl-click" and configuring the touchpad to recognize two taps at once as a secondary click. I don't have a mouse for the mac, just the touchpad.</p>
<p>MAC OS 10.4.10 tiger </p>
<p>Python/IDLE version 2.6.1</p>
<p>I have tried STFW unsuccessfully...</p>
| 2 | 2009-07-04T05:00:20Z | 4,251,733 | <p>It's a bug in <code>IDLE</code>, specifically any <code>IDLE</code> on Mac OS X linked with the default Aqua <code>Tk</code>, supplied with Mac OS X or from ActiveState. That includes the Apple-supplied Pythons in OS X 10.4 through 10.6 and the python.org installers. The problem is that Aqua <code>Tk</code> has a different mapping for mouse clicks and, even if that were fixed, <code>IDLE</code> expects users to always have a multi-button mouse. See <a href="http://bugs.python.org/issue10404" rel="nofollow">Issue 10404</a> for more details and a patch. This should not be an issue if the Python is linked with an X11-based <code>Tk</code>, as is the default with <a href="http://trac.macports.org/browser/trunk/dports/x11/tk/Portfile" rel="nofollow">MacPorts</a>.</p>
| 1 | 2010-11-23T00:49:03Z | [
"python",
"osx",
"python-idle"
] |
Python: How to set breakpoints on mac with IDLE debugger? | 1,081,536 | <p>I have access to both a PC and a mac for a python class. I find I am unable to set breakpoints in the IDLE debugger in the mac (works fine on the PC). </p>
<p>I've tried "ctrl-click" and configuring the touchpad to recognize two taps at once as a secondary click. I don't have a mouse for the mac, just the touchpad.</p>
<p>MAC OS 10.4.10 tiger </p>
<p>Python/IDLE version 2.6.1</p>
<p>I have tried STFW unsuccessfully...</p>
| 2 | 2009-07-04T05:00:20Z | 6,274,526 | <p>So, for newbies, a little more detail on Ned Deily's patch. Here is what I did. I'm running python 2.7.1 in idle on osx 10.6.5. I followed Ned's link for Issue 10404, and finally to the patched version of the file EditorWindow.py, which on my installation lives in the directory</p>
<p>/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/idlelib</p>
<p>Following more links, we find the patched version of the file is <a href="http://hg.python.org/cpython/file/5f49d3cb194f/Lib/idlelib/EditorWindow.py" rel="nofollow">here</a>.</p>
<p>This you can download from the "raw" link to the left on that page. Keep a copy of your old version of EditorWindow.py, then move or copy the new EditorWindow.py from your Download directory to the idlelib directory. Restart idle, and ctrl-click gives drop-down menus for setting breakpoints. This is probably all obvious, but it's the first time I did it so I thought I'd share the mini-steps with other novices. There may be a cleaner way to do it too of course.</p>
| 0 | 2011-06-08T05:22:18Z | [
"python",
"osx",
"python-idle"
] |
Transition from Python2.4 to Python2.6 on CentOS. Module migration problem | 1,081,698 | <p>Hey guys, I have a problem of upgrading python from 2.4 to 2.6:</p>
<p>I have CentOS 5 (Full)
<br>It has python 2.4 living in /usr/lib/python2.4/
<br>Additional modules are living in /usr/lib/python2.4/site-packages/</p>
<p>I've built python 2.6 from sources at /usr/local/lib/python2.6/
<br>I've set default python to python2.6
<br>Now old modules for 2.4 are out of pythonpath and are "lost"
<br>In particular, yum is broken ("no module named yum")</p>
<p>So what is the right way to migrate/install modules to python2.6? </p>
| 3 | 2009-07-04T06:59:05Z | 1,081,705 | <p>There are a couple of options...</p>
<ol>
<li><p>If the modules will run under Python 2.6, you can simply create symbolic links to them from the 2.6 site-packages directory to the 2.4 site-packages directory.</p></li>
<li><p>If they will not run under 2.6, then you may need to re-compile them against 2.6, or install up-to-date versions of them. Just make sure you are using 2.6 when calling <code>"python setup.py"</code></p></li>
</ol>
<p>...</p>
<p>You may want to post this on serverfault.com, if you run into additional challenges.</p>
| 0 | 2009-07-04T07:04:44Z | [
"python",
"linux",
"upgrade",
"centos",
"python-2.6"
] |
Transition from Python2.4 to Python2.6 on CentOS. Module migration problem | 1,081,698 | <p>Hey guys, I have a problem of upgrading python from 2.4 to 2.6:</p>
<p>I have CentOS 5 (Full)
<br>It has python 2.4 living in /usr/lib/python2.4/
<br>Additional modules are living in /usr/lib/python2.4/site-packages/</p>
<p>I've built python 2.6 from sources at /usr/local/lib/python2.6/
<br>I've set default python to python2.6
<br>Now old modules for 2.4 are out of pythonpath and are "lost"
<br>In particular, yum is broken ("no module named yum")</p>
<p>So what is the right way to migrate/install modules to python2.6? </p>
| 3 | 2009-07-04T06:59:05Z | 1,081,903 | <p>They are not broken, they are simply not installed. The solution to that is to install them under 2.6. But first we should see if you really should do that...</p>
<p>Yes, Python will when installed replace the python command to the version installed (unless you run it with --alt-install). You don't exactly state what your problem is, so I'm going to guess. Your problem is that many local commands using Python now fail, because they get executed with Python 2.6, and not with Python 2.4. Is that correct?</p>
<p>If that is so, then simply delete /usr/local/bin/python, and make sure /usr/bin/python is a symbolic link to /usr/bin/python2.4. Then you would have to type python2.6 to run python2,6, but that's OK. That's the best way to do it. Then you only need to install the packages <strong>you</strong> need in 2.6.</p>
<p>But if my guess is wrong, and you really need to install all those packages under 2.6, then don't worry too much. First of all, install setuptools. It includes an easy_install script, and you can then install modules with </p>
<pre><code>easy_install <modulename>
</code></pre>
<p>It will download the module from pypi.python.org and install it. And it will also install any module that is a dependency. easy_install can install any module that is using distutils as an installer, and not many don't. This will make installing 90% of those modules a breeze.</p>
<p>If the module has a C-component, it will compile it, and then you need the library headers too, and that will be more work, and all you can do there is install them the standard CentOS way.</p>
<p>You shouldn't use symbolic links between versions, because libraries are generally for a particular version. For 2.4 and 2.6 I think the .pyc files are compatible (but I'm not 100% sure), so that may work, but any module who uses C <em>will</em> break. And other versions of Python will have incompatible .pyc files as well. And I'm sure that if you do that, most Python people are not going to help you if you do it. ;-)</p>
<p>In general, I try too keep the system python "clean", I.e. I don't install anything there that isn't installed with the packaging tools. Instead I use virtualenv or buildout to let every application have their own python path where it's dependencies live. So every single project I have basically has it's own set of libraries. It gets easier that way.</p>
| 3 | 2009-07-04T09:46:06Z | [
"python",
"linux",
"upgrade",
"centos",
"python-2.6"
] |
Transition from Python2.4 to Python2.6 on CentOS. Module migration problem | 1,081,698 | <p>Hey guys, I have a problem of upgrading python from 2.4 to 2.6:</p>
<p>I have CentOS 5 (Full)
<br>It has python 2.4 living in /usr/lib/python2.4/
<br>Additional modules are living in /usr/lib/python2.4/site-packages/</p>
<p>I've built python 2.6 from sources at /usr/local/lib/python2.6/
<br>I've set default python to python2.6
<br>Now old modules for 2.4 are out of pythonpath and are "lost"
<br>In particular, yum is broken ("no module named yum")</p>
<p>So what is the right way to migrate/install modules to python2.6? </p>
| 3 | 2009-07-04T06:59:05Z | 1,082,045 | <p>Some Python libs may be still not accessible as with Python 2.6 <code>site-packages</code> is changed to <code>dist-packages</code>. </p>
<p>The only way in that case is to do move all stuff generated in site-packages (e.g. by <code>make install</code>) to dist-packages and create a sym-link.</p>
| 0 | 2009-07-04T11:40:09Z | [
"python",
"linux",
"upgrade",
"centos",
"python-2.6"
] |
Transition from Python2.4 to Python2.6 on CentOS. Module migration problem | 1,081,698 | <p>Hey guys, I have a problem of upgrading python from 2.4 to 2.6:</p>
<p>I have CentOS 5 (Full)
<br>It has python 2.4 living in /usr/lib/python2.4/
<br>Additional modules are living in /usr/lib/python2.4/site-packages/</p>
<p>I've built python 2.6 from sources at /usr/local/lib/python2.6/
<br>I've set default python to python2.6
<br>Now old modules for 2.4 are out of pythonpath and are "lost"
<br>In particular, yum is broken ("no module named yum")</p>
<p>So what is the right way to migrate/install modules to python2.6? </p>
| 3 | 2009-07-04T06:59:05Z | 1,085,044 | <p>easy_install is good one but there are low level way for installing module, just:</p>
<ol>
<li>unpack module source to some directory</li>
<li>type "python setup.py install"</li>
</ol>
<p>Of course you should do this with required installed python interpreter version; for checking it type:</p>
<p>python -V</p>
| 0 | 2009-07-05T23:19:16Z | [
"python",
"linux",
"upgrade",
"centos",
"python-2.6"
] |
PYTHON: Update MULTIPLE COLUMNS with python variables | 1,081,750 | <p>I'm trying to write a valid mysql statement that would allow me to update multiple columns in one record with values provided as python variables.</p>
<p>My statement would look like this:</p>
<pre><code>db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="dbname")
cursor = db.cursor()
sql_update = "UPDATE table_name SET field1=%s, field2=%s, field3=%s, field4=%s, field5=%s, field6=%s, field7=%s, field8=%s, field9=%s, field10=%s WHERE id=%s" % (var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, id)
cursor.execute(sql_update)
cursor.close ()
db.commit()
db.close()
</code></pre>
<p>While trying to execute the query I keep receiving information that there is an error in my SQL syntax. I can't locate it though.
Please, maybe someone can point me my mistake or show me how it should be written?</p>
| 0 | 2009-07-04T07:42:43Z | 1,081,760 | <p>You are using string formatting, while what you SHOULD be doing is using a parametrized query. Do it like this:</p>
<pre><code>cursor.execute("UPDATE table_name SET field1=%s ... field10=%s WHERE id=%s", (var1,... var10, id))
</code></pre>
<p>Did you really need to post it with 10 variables? It was so frustrating to format, I gave up.</p>
| 5 | 2009-07-04T07:53:12Z | [
"python",
"mysql",
"variables"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.