title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How can I get a list of locally installed Python modules? | 739,993 | 533 | 2009-04-11T12:34:18Z | 23,885,252 | 260 | 2014-05-27T09:05:42Z | [
"python",
"module",
"pip"
] | I would like to get a list of Python modules, which are in my Python installation (UNIX server).
**How can you get a list of Python modules installed in your computer?** | ## Solution
My 50 cents for getting a `pip freeze`-like list from a Python script:
```
import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
for i in installed_packages])
print(installed_packages_list)
```
As a (too long) one liner:
``... |
How to check if one of the following items is in a list? | 740,287 | 104 | 2009-04-11T15:13:07Z | 740,291 | 15 | 2009-04-11T15:16:29Z | [
"python"
] | I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.
```
>>> a = [2,3,4]
>>> print (1 or 2) in a
False
>>> print (2 or 1) in a
True
``` | Think about what the code actually says!
```
>>> (1 or 2)
1
>>> (2 or 1)
2
```
That should probably explain it. :) Python apparently implements "lazy or", which should come as no surprise. It performs it something like this:
```
def or(x, y):
if x: return x
if y: return y
return False
```
In the first e... |
How to check if one of the following items is in a list? | 740,287 | 104 | 2009-04-11T15:13:07Z | 740,294 | 119 | 2009-04-11T15:22:07Z | [
"python"
] | I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.
```
>>> a = [2,3,4]
>>> print (1 or 2) in a
False
>>> print (2 or 1) in a
True
``` | ```
>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i in L2]
[2]
>>> S1 = set(L1)
>>> S2 = set(L2)
>>> S1.intersection(S2)
set([2])
```
Both empty lists and empty sets are False, so you can use the value directly as a truth value. |
How to check if one of the following items is in a list? | 740,287 | 104 | 2009-04-11T15:13:07Z | 740,359 | 12 | 2009-04-11T16:12:42Z | [
"python"
] | I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.
```
>>> a = [2,3,4]
>>> print (1 or 2) in a
False
>>> print (2 or 1) in a
True
``` | Maybe a bit more lazy:
```
a = [1,2,3,4]
b = [2,7]
print any((True for x in a if x in b))
``` |
How to check if one of the following items is in a list? | 740,287 | 104 | 2009-04-11T15:13:07Z | 740,384 | 103 | 2009-04-11T16:30:38Z | [
"python"
] | I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.
```
>>> a = [2,3,4]
>>> print (1 or 2) in a
False
>>> print (2 or 1) in a
True
``` | Ah, Tobias you beat me to it. I was thinking of this slight variation on your solution:
```
print any(x in a for x in b)
``` |
How to check if one of the following items is in a list? | 740,287 | 104 | 2009-04-11T15:13:07Z | 22,682,523 | 7 | 2014-03-27T08:56:02Z | [
"python"
] | I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.
```
>>> a = [2,3,4]
>>> print (1 or 2) in a
False
>>> print (2 or 1) in a
True
``` | ```
a = {2,3,4}
if {1,2} & a:
pass
```
Code golf version. Consider using a set if it makes sense to do so.
I find this more readable than a list comprehension. |
python write string directly to tarfile | 740,820 | 21 | 2009-04-11T21:41:08Z | 740,839 | 24 | 2009-04-11T21:48:26Z | [
"python",
"file",
"file-io",
"tar"
] | Is there a way to write a string directly to a tarfile? From <http://docs.python.org/library/tarfile.html> it looks like only files already written to the file system can be added. | I would say it's possible, by playing with TarInfo e TarFile.addfile passing a StringIO as a fileobject.
Very rough, but works
```
import tarfile
import StringIO
tar = tarfile.TarFile("test.tar","w")
string = StringIO.StringIO()
string.write("hello")
string.seek(0)
info = tarfile.TarInfo(name="foo")
info.size=len(s... |
python write string directly to tarfile | 740,820 | 21 | 2009-04-11T21:41:08Z | 740,854 | 9 | 2009-04-11T22:02:46Z | [
"python",
"file",
"file-io",
"tar"
] | Is there a way to write a string directly to a tarfile? From <http://docs.python.org/library/tarfile.html> it looks like only files already written to the file system can be added. | As Stefano pointed out, you can use `TarFile.addfile` and `StringIO`.
```
import tarfile, StringIO
data = 'hello, world!'
tarinfo = tarfile.TarInfo('test.txt')
tarinfo.size = len(data)
tar = tarfile.open('test.tar', 'a')
tar.addfile(tarinfo, StringIO.StringIO(data))
tar.close()
```
You'll probably want to fill oth... |
How do I tell matplotlib that I am done with a plot? | 741,877 | 92 | 2009-04-12T14:40:55Z | 741,884 | 81 | 2009-04-12T14:43:47Z | [
"python",
"matplotlib",
"plot"
] | The following code plots to two [PostScript](http://en.wikipedia.org/wiki/PostScript) (.ps) files, but the second one contains both lines.
```
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(111)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.sa... | You can use `figure` to create a new plot, for example, or use `close` after the first plot. |
How do I tell matplotlib that I am done with a plot? | 741,877 | 92 | 2009-04-12T14:40:55Z | 742,062 | 109 | 2009-04-12T17:08:30Z | [
"python",
"matplotlib",
"plot"
] | The following code plots to two [PostScript](http://en.wikipedia.org/wiki/PostScript) (.ps) files, but the second one contains both lines.
```
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(111)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.sa... | There is a clear figure command, and it should do it for you:
```
plt.clf()
```
If you have multiple subplots in the same figure
```
plt.cla()
```
clears the current axes. |
How do I tell matplotlib that I am done with a plot? | 741,877 | 92 | 2009-04-12T14:40:55Z | 742,489 | 20 | 2009-04-12T21:44:36Z | [
"python",
"matplotlib",
"plot"
] | The following code plots to two [PostScript](http://en.wikipedia.org/wiki/PostScript) (.ps) files, but the second one contains both lines.
```
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(111)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.sa... | As stated from David Cournapeau, use figure().
```
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.figure()
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")
plt.figure()
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=1... |
How do I tell matplotlib that I am done with a plot? | 741,877 | 92 | 2009-04-12T14:40:55Z | 9,820,820 | 11 | 2012-03-22T10:52:09Z | [
"python",
"matplotlib",
"plot"
] | The following code plots to two [PostScript](http://en.wikipedia.org/wiki/PostScript) (.ps) files, but the second one contains both lines.
```
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(111)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.sa... | Just enter `plt.hold(False)` before the first plt.plot, and you can stick to your original code. |
Programatically determining amount of parameters a function requires - Python | 741,950 | 30 | 2009-04-12T15:43:34Z | 741,957 | 34 | 2009-04-12T15:48:52Z | [
"python",
"parameters",
"function"
] | I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed t... | [inspect.getargspec()](http://docs.python.org/library/inspect.html#inspect.getargspec):
> Get the names and default values of a functionâs arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the nam... |
Programatically determining amount of parameters a function requires - Python | 741,950 | 30 | 2009-04-12T15:43:34Z | 741,961 | 13 | 2009-04-12T15:53:40Z | [
"python",
"parameters",
"function"
] | I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed t... | What you want is in general not possible, because of the use of varargs and kwargs, but `inspect.getargspec` (Python 2.x) and `inspect.getfullargspec` (Python 3.x) come close.
* Python 2.x:
```
>>> import inspect
>>> def add(a, b=0):
... return a + b
...
>>> inspect.getargspec(add)
(['a', 'b'], None... |
Python strange behavior in for loop or lists | 742,371 | 7 | 2009-04-12T20:30:22Z | 742,383 | 28 | 2009-04-12T20:36:58Z | [
"python",
"list",
"foreach"
] | I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example:
```
x = [1,2,2,2,2]... | This is a well-documented behaviour in Python, that you aren't supposed to modify the list being iterated through. Try this instead:
```
for i in x[:]:
x.remove(i)
```
The `[:]` returns a "slice" of `x`, which happens to contain all its elements, and is thus effectively a copy of `x`. |
Python strange behavior in for loop or lists | 742,371 | 7 | 2009-04-12T20:30:22Z | 742,386 | 10 | 2009-04-12T20:37:18Z | [
"python",
"list",
"foreach"
] | I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example:
```
x = [1,2,2,2,2]... | When you delete an element, and the for-loop incs to the next index, you then skip an element.
Do it backwards. Or please state your real problem. |
Immutability and thread safety in Python | 742,882 | 4 | 2009-04-13T02:25:58Z | 742,899 | 15 | 2009-04-13T02:35:47Z | [
"python",
"multithreading",
"immutability"
] | I'm cleaning some of the Python code I wrote when I was...not as knowledgeable. Primarily I am killing some of the complexity that stemmed from an incomplete understanding of threading in Python. I need to make a list of items thread-safe, and I'd like to do it via immutable lists, instead of the usual locking approach... | First of all, appending to a list is already thread-safe in the CPython reference implementation of the Python programming language. In other words, while the language specification doesn't require that the list class be thread-safe, it is anyway. So unless you're using Jython or IronPython or some other Python impleme... |
Emulate a do-while loop in Python? | 743,164 | 357 | 2009-04-13T06:18:42Z | 743,186 | 449 | 2009-04-13T06:28:43Z | [
"python",
"while-loop",
"do-while"
] | I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
```
l = [ 1, 2, 3 ]
i = l.__iter__()
s = None
while True :
if s :
print s
try :
s = i.next()
except StopIteration :
break
print "done"
```
Instead of "1,2,3,done", it prints the fo... | I am not sure what you are trying to do. You can implement a do-while loop like this:
```
while True:
stuff()
if fail_condition:
break
```
Or:
```
stuff()
while not fail_condition:
stuff()
```
What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:
```
for i in ... |
Emulate a do-while loop in Python? | 743,164 | 357 | 2009-04-13T06:18:42Z | 743,231 | 22 | 2009-04-13T07:06:40Z | [
"python",
"while-loop",
"do-while"
] | I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
```
l = [ 1, 2, 3 ]
i = l.__iter__()
s = None
while True :
if s :
print s
try :
s = i.next()
except StopIteration :
break
print "done"
```
Instead of "1,2,3,done", it prints the fo... | Exception will break the loop, so you might as well handle it outside the loop.
```
try:
while True:
if s:
print s
s = i.next()
except StopIteration:
pass
```
I guess that the problem with your code is that behaviour of `break` inside `except` is not defined. Generally `break` goes only one level... |
Emulate a do-while loop in Python? | 743,164 | 357 | 2009-04-13T06:18:42Z | 743,944 | 20 | 2009-04-13T13:57:02Z | [
"python",
"while-loop",
"do-while"
] | I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
```
l = [ 1, 2, 3 ]
i = l.__iter__()
s = None
while True :
if s :
print s
try :
s = i.next()
except StopIteration :
break
print "done"
```
Instead of "1,2,3,done", it prints the fo... | ```
do {
stuff()
} while (condition())
```
->
```
while True:
stuff()
if not condition():
break
```
You can do a function:
```
def do_while(stuff, condition):
while condition(stuff()):
pass
```
But
1) It's ugly.
2) Condition should be a function with one parameter, supposed to be filled by stuff (i... |
Emulate a do-while loop in Python? | 743,164 | 357 | 2009-04-13T06:18:42Z | 1,662,604 | 13 | 2009-11-02T17:32:02Z | [
"python",
"while-loop",
"do-while"
] | I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
```
l = [ 1, 2, 3 ]
i = l.__iter__()
s = None
while True :
if s :
print s
try :
s = i.next()
except StopIteration :
break
print "done"
```
Instead of "1,2,3,done", it prints the fo... | Here is a crazier solution of a different pattern -- using coroutines. The code is still very similar, but with one important difference; there are no exit conditions at all! The coroutine (chain of coroutines really) just stops when you stop feeding it with data.
```
def coroutine(func):
"""Coroutine decorator
... |
Emulate a do-while loop in Python? | 743,164 | 357 | 2009-04-13T06:18:42Z | 2,440,643 | 152 | 2010-03-14T00:09:54Z | [
"python",
"while-loop",
"do-while"
] | I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
```
l = [ 1, 2, 3 ]
i = l.__iter__()
s = None
while True :
if s :
print s
try :
s = i.next()
except StopIteration :
break
print "done"
```
Instead of "1,2,3,done", it prints the fo... | Here's a very simple way to emulate a do-while loop:
```
condition = True
while condition:
# loop body here
condition = test_loop_condition()
# end of loop
```
The key features of a do-while loop are that the loop body always executes at least once, and that the condition is evaluated at the bottom of the loo... |
Emulate a do-while loop in Python? | 743,164 | 357 | 2009-04-13T06:18:42Z | 5,957,047 | 8 | 2011-05-10T22:03:06Z | [
"python",
"while-loop",
"do-while"
] | I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
```
l = [ 1, 2, 3 ]
i = l.__iter__()
s = None
while True :
if s :
print s
try :
s = i.next()
except StopIteration :
break
print "done"
```
Instead of "1,2,3,done", it prints the fo... | for a do - while loop containing try statements
```
loop = True
while loop:
generic_stuff()
try:
questionable_stuff()
# to break from successful completion
# loop = False
except:
optional_stuff()
# to break from unsuccessful completion -
# the case referenced in t... |
Emulate a do-while loop in Python? | 743,164 | 357 | 2009-04-13T06:18:42Z | 27,095,765 | 14 | 2014-11-23T23:37:17Z | [
"python",
"while-loop",
"do-while"
] | I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
```
l = [ 1, 2, 3 ]
i = l.__iter__()
s = None
while True :
if s :
print s
try :
s = i.next()
except StopIteration :
break
print "done"
```
Instead of "1,2,3,done", it prints the fo... | My code below might be a useful implementation, highlighting the main difference between [do-while](/questions/tagged/do-while "show questions tagged 'do-while'") vs [while](/questions/tagged/while "show questions tagged 'while'") as I understand it.
So in this one case, you always go through the loop at least once.
... |
Split string into a list in Python | 743,806 | 217 | 2009-04-13T12:48:44Z | 743,807 | 196 | 2009-04-13T12:50:21Z | [
"python",
"list",
"split",
"text-segmentation"
] | I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?
```
def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word i... | Splits the string in `text` on delimiter: `" "`.
```
words = text.split()
```
Split the string in `text` on delimiter: `","`.
```
words = text.split(",")
```
The words variable will be a list datatype and contain a list of words from `text` split on the delimiter. |
Split string into a list in Python | 743,806 | 217 | 2009-04-13T12:48:44Z | 743,823 | 178 | 2009-04-13T12:54:16Z | [
"python",
"list",
"split",
"text-segmentation"
] | I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?
```
def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word i... | ```
text.split()
```
This should be enough to store each word in a list. `words` is already a list of the words from the sentence, so there is no need for the loop.
Second, it might be a typo, but you have your loop a little messed up. If you really did want to use append, it would be:
```
words.append(word)
```
no... |
Split string into a list in Python | 743,806 | 217 | 2009-04-13T12:48:44Z | 743,824 | 47 | 2009-04-13T12:54:58Z | [
"python",
"list",
"split",
"text-segmentation"
] | I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?
```
def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word i... | [str.split()](https://docs.python.org/2/library/stdtypes.html#str.split)
> Return a **list of the words** in the string, using sep as the delimiter
> ... If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result wil... |
Split string into a list in Python | 743,806 | 217 | 2009-04-13T12:48:44Z | 743,922 | 9 | 2009-04-13T13:46:06Z | [
"python",
"list",
"split",
"text-segmentation"
] | I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?
```
def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word i... | > I want my python function to split a sentence (input) and store each word in a list
The `str().split()` method does this, it takes a string, splits it into a list:
```
>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")
>>> print(words)
['this', 'is', 'a', 'sentence']
>>> type(words)
<type 'list... |
Split string into a list in Python | 743,806 | 217 | 2009-04-13T12:48:44Z | 744,046 | 35 | 2009-04-13T14:24:18Z | [
"python",
"list",
"split",
"text-segmentation"
] | I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?
```
def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word i... | Depending on what you plan to do with your sentence-as-a-list, you may want to look at the [Natural Language Took Kit](http://www.nltk.org/). It deals heavily with text processing and evaluation. You can also use it to solve your problem:
```
import nltk
words = nltk.word_tokenize(raw_sentence)
```
This has the added... |
Split string into a list in Python | 743,806 | 217 | 2009-04-13T12:48:44Z | 17,951,315 | 16 | 2013-07-30T15:32:43Z | [
"python",
"list",
"split",
"text-segmentation"
] | I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?
```
def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word i... | How about this algorithm? Split text on whitespace, then trim punctuation. This carefully removes punctuation from the edge of words, without harming apostrophes inside words such as `we're`.
```
>>> text
"'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'"
>>> text.split()
["'Oh,", '... |
Reading Huge File in Python | 744,256 | 12 | 2009-04-13T15:28:04Z | 744,284 | 11 | 2009-04-13T15:37:33Z | [
"python",
"performance",
"file-io",
"large-files"
] | I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.
My current approach is included below. It takes 30 seconds. There must be more efficient P... | If you only need 200 of 50 million lines, then reading all of it into memory is a waste. I would sort the list of search keys and then apply binary search to the file using seek() or something similar. This way you would not read the entire file to memory which I think should speed things up. |
Reading Huge File in Python | 744,256 | 12 | 2009-04-13T15:28:04Z | 744,309 | 7 | 2009-04-13T15:46:13Z | [
"python",
"performance",
"file-io",
"large-files"
] | I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.
My current approach is included below. It takes 30 seconds. There must be more efficient P... | Slight optimization of S.Lotts answer:
```
from collections import defaultdict
keyValues= defaultdict(list)
targetKeys= # some list of keys as strings
for line in fin:
key, value = line.split()
if key in targetKeys:
keyValues[key].append( value )
```
Since we're using a dictionary rather than a list, ... |
Imports in python are static, any solution? | 744,325 | 4 | 2009-04-13T15:52:59Z | 744,369 | 8 | 2009-04-13T16:05:56Z | [
"python"
] | foo.py :
```
i = 10
def fi():
global i
i = 99
```
bar.py :
```
import foo
from foo import i
print i, foo.i
foo.fi()
print i, foo.i
```
This is problematic. Why does `i` not change when `foo.i` changes? | What Ross is saying is to restucture foo like so:
```
_i = 10
def getI():
return _i
def fi():
global _i
_i = 99
```
Then you will see it works the way you want:
```
>>> import foo
>>> print foo.getI()
10
>>> foo.fi()
>>> print foo.getI()
99
```
It is also 'better' in the sense that you avoid exporting... |
Imports in python are static, any solution? | 744,325 | 4 | 2009-04-13T15:52:59Z | 744,407 | 7 | 2009-04-13T16:15:33Z | [
"python"
] | foo.py :
```
i = 10
def fi():
global i
i = 99
```
bar.py :
```
import foo
from foo import i
print i, foo.i
foo.fi()
print i, foo.i
```
This is problematic. Why does `i` not change when `foo.i` changes? | What `import` does in `bar.py` is set up an identifier called `i` in the `bar.py` module namespace that points to the same address as the identifier called `i` in the `foo.py` module namespace.
This is an important distinction... `bar.i` is not pointing to `foo.i`, but rather to the same space in memory where the obje... |
Circular (or cyclic) imports in Python | 744,373 | 197 | 2009-04-13T16:07:07Z | 744,403 | 183 | 2009-04-13T16:15:00Z | [
"python",
"circular-dependency",
"cyclic-reference"
] | What will happen if two modules import each other?
To generalize the problem, what about the cyclic imports in Python? | There was a really good discussion on this over at [comp.lang.python](http://groups.google.com/group/comp.lang.python/browse_thread/thread/1d80a1c6db2b867c) last year. It answers your question pretty thoroughly.
> Imports are pretty straightforward really. Just remember the following:
>
> 'import' and 'from xxx import... |
Circular (or cyclic) imports in Python | 744,373 | 197 | 2009-04-13T16:07:07Z | 744,410 | 63 | 2009-04-13T16:16:23Z | [
"python",
"circular-dependency",
"cyclic-reference"
] | What will happen if two modules import each other?
To generalize the problem, what about the cyclic imports in Python? | Cyclic imports terminate, but you need to be careful not to use the cyclically-imported modules during module initialization.
Consider the following files:
a.py:
```
print "a in"
import sys
print "b imported: %s" % ("b" in sys.modules, )
import b
print "a out"
```
b.py:
```
print "b in"
import a
print "b out"
x = ... |
Circular (or cyclic) imports in Python | 744,373 | 197 | 2009-04-13T16:07:07Z | 746,067 | 155 | 2009-04-14T02:03:43Z | [
"python",
"circular-dependency",
"cyclic-reference"
] | What will happen if two modules import each other?
To generalize the problem, what about the cyclic imports in Python? | If you do `import foo` inside `bar` and `import bar` inside `foo`, it will work fine. By the time anything actually runs, both modules will be fully loaded and will have references to each other.
The problem is when instead you do `from foo import abc` and `from bar import xyz`. Because now each module requires the ot... |
Circular (or cyclic) imports in Python | 744,373 | 197 | 2009-04-13T16:07:07Z | 33,547,682 | 11 | 2015-11-05T14:51:51Z | [
"python",
"circular-dependency",
"cyclic-reference"
] | What will happen if two modules import each other?
To generalize the problem, what about the cyclic imports in Python? | As other answers describe this pattern is acceptable in python:
```
def dostuff(self):
from foo import bar
...
```
Which will avoid the execution of the import statement when the file is imported by other modules. Only if there is a logical circular dependency, this will fail.
Most Circular Imports are not... |
Django models - how to filter out duplicate values by PK after the fact? | 744,424 | 6 | 2009-04-13T16:20:47Z | 747,611 | 12 | 2009-04-14T13:40:00Z | [
"python",
"django",
"data-structures",
"set",
"unique"
] | I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto\_increment int PK), but I can't use set() because they aren't hashable.
Is there a quick and easy way to do this? I'm considering using a dict instead of a lis... | In general it's better to combine all your queries into a single query if possible. Ie.
```
q = Model.objects.filter(Q(field1=f1)|Q(field2=f2))
```
instead of
```
q1 = Models.object.filter(field1=f1)
q2 = Models.object.filter(field2=f2)
```
If the first query is returning duplicated Models then use distinct()
```
... |
Calling unknown Python functions | 744,626 | 6 | 2009-04-13T17:12:47Z | 744,634 | 15 | 2009-04-13T17:15:39Z | [
"python"
] | This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.
How do I call a function from a string, i.e.
```
functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
``` | how do you not know the name of the function to call? Store the functions instead of the name:
```
functions_to_call = [int, str, float]
value = 33.5
for function in functions_to_call:
print "calling", function
print "result:", function(value)
``` |
Calling unknown Python functions | 744,626 | 6 | 2009-04-13T17:12:47Z | 744,647 | 8 | 2009-04-13T17:17:50Z | [
"python"
] | This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.
How do I call a function from a string, i.e.
```
functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
``` | Something like that...when i was looking at function pointers in python..
```
def myfunc(x):
print x
dict = {
"myfunc": myfunc
}
dict["myfunc"]("hello")
func = dict.get("myfunc")
if callable(func):
func(10)
``` |
Calling unknown Python functions | 744,626 | 6 | 2009-04-13T17:12:47Z | 744,686 | 19 | 2009-04-13T17:31:15Z | [
"python"
] | This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.
How do I call a function from a string, i.e.
```
functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
``` | You can use the python builtin locals() to get local declarations, eg:
```
def f():
print "Hello, world"
def g():
print "Goodbye, world"
for fname in ["f", "g"]:
fn = locals()[fname]
print "Calling %s" % (fname)
fn()
```
You can use the "imp" module to load functions from user-specified python f... |
Create function through MySQLdb | 745,538 | 10 | 2009-04-13T21:54:10Z | 745,575 | 15 | 2009-04-13T22:10:30Z | [
"python",
"mysql"
] | How can I define a multi-statement function or procedure in using the MySQLdb lib in python?
Example:
```
import MySQLdb
db = MySQLdb.connect(db='service')
c = db.cursor()
c.execute("""DELIMITER //
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 THEN
RETURN 0.0;
... | The `DELIMITER` command is a MySQL shell client builtin, and it's recognized only by that program (and MySQL Query Browser). It's not necessary to use `DELIMITER` if you execute SQL statements directly through an API.
The purpose of `DELIMITER` is to help you avoid ambiguity about the termination of the `CREATE FUNCTI... |
Is Python interpreted (like Javascript or PHP)? | 745,743 | 28 | 2009-04-13T23:15:37Z | 745,749 | 47 | 2009-04-13T23:17:31Z | [
"python"
] | Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)? | There's multiple questions here:
1. No, Python is not interpreted. The standard implementation compiles to bytecode, and then executes in a virtual machine. Many modern JavaScript engines also do this.
2. Regardless of implementation (interpreter, VM, machine code), anything you want can run in the background. You can... |
Is Python interpreted (like Javascript or PHP)? | 745,743 | 28 | 2009-04-13T23:15:37Z | 745,789 | 19 | 2009-04-13T23:30:23Z | [
"python"
] | Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)? | Technically, Python is compiled to bytecode and then interpreted in a [virtual machine](http://en.wikipedia.org/wiki/Virtual_machine). If the Python compiler is able to write out the bytecode into a .pyc file, it will (usually) do so.
On the other hand, there's no explicit compilation step in Python as there is with J... |
Is Python interpreted (like Javascript or PHP)? | 745,743 | 28 | 2009-04-13T23:15:37Z | 749,218 | 64 | 2009-04-14T20:23:11Z | [
"python"
] | Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)? | As the varied responses will tell you, the line between interpreted and compiled is no longer as clear as it was when such terms were coined. In fact, it's also something of a mistake to consider *languages* as being either interpreted or compiled, as different *implementations* of languages may do different things. Th... |
wxPython: Calling an event manually | 747,781 | 16 | 2009-04-14T14:14:27Z | 748,801 | 8 | 2009-04-14T18:28:22Z | [
"python",
"user-interface",
"events",
"wxpython"
] | How can I call a specific event manually from my own code? | I think you want [wx.PostEvent](http://www.wxpython.org/docs/api/wx-module.html#PostEvent).
There's also some info about posting events from other thread for [long running tasks on the wxPython wiki](http://wiki.wxpython.org/LongRunningTasks). |
wxPython: Calling an event manually | 747,781 | 16 | 2009-04-14T14:14:27Z | 841,045 | 45 | 2009-05-08T17:55:39Z | [
"python",
"user-interface",
"events",
"wxpython"
] | How can I call a specific event manually from my own code? | Old topic, but I think I've got this figured out after being confused about it for a long time, so if anyone else comes through here looking for the answer, this might help.
To manually post an event, you can use
```
self.GetEventHandler().ProcessEvent(event)
```
(wxWidgets docs [here](http://docs.wxwidgets.org/stab... |
Python borg pattern problem | 747,793 | 6 | 2009-04-14T14:17:36Z | 747,888 | 13 | 2009-04-14T14:33:32Z | [
"python",
"design-patterns"
] | I'm having problems implementing a borg in python. I found an example in an answer to [this question](http://stackoverflow.com/questions/736335/python-superglobal) but it's not working for me, unless I'm missing something. Here's the code:
```
class Config:
"""
Borg singleton config object
"""
__we_are... | It looks like it's working rather too well :-)
The issue is that the assignment `self.__myvalue = ""` in `__init__` will always clobber the value of `myvalue` every time a new Borg is, er, created. You can see this if you add some additional print statements to your test:
```
conf = Config()
conf.myvalue("Hello")
pri... |
How to get output of exe in python script? | 748,028 | 4 | 2009-04-14T15:02:33Z | 748,058 | 14 | 2009-04-14T15:09:02Z | [
"python",
"ide",
"executable",
"redirect"
] | When I call an external `.exe` program in Python, how can I get `printf` output from the `.exe` application and print it to my Python IDE? | To call an external program from Python, use the [subprocess](http://docs.python.org/library/subprocess.html#module-subprocess) module.
> The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
An example from the doc (`output` is a file objec... |
benchmarking django apps | 748,130 | 13 | 2009-04-14T15:26:16Z | 748,177 | 7 | 2009-04-14T15:39:50Z | [
"python",
"django",
"profiling"
] | I'm interested in testing the performance of my django apps as I go, what is the best way to get line by line performance data?
**note**: Googling this returns lots of people benchmarking django itself. I'm not looking for a benchmarks of django, I'm trying to test the performance of the django apps that I'm writing :... | There's two layers to this. We have most of #1 in place for our testing. We're about to start on #2.
1. Django in isolation. The ordinary Django unit tests works well here. Create some tests that cycle through a few (less than 6) "typical" use cases. Get this, post that, etc. Collect timing data. This isn't real web p... |
Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS | 748,324 | 12 | 2009-04-14T16:14:04Z | 748,340 | 32 | 2009-04-14T16:17:56Z | [
"python",
"bit.ly",
"tinyurl"
] | I am just learning python and is interested in how this can be accomplished. During the search for the answer, I came across this service: <http://www.longurlplease.com>
For example:
<http://bit.ly/rgCbf> can be converted to:
<http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place>
I did s... | Enter [`urllib2`](http://docs.python.org/library/urllib2.html), which offers the easiest way of doing this:
```
>>> import urllib2
>>> fp = urllib2.urlopen('http://bit.ly/rgCbf')
>>> fp.geturl()
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'
```
For reference's sake, however, note ... |
How do I create a datetime in Python from milliseconds? | 748,491 | 53 | 2009-04-14T17:01:03Z | 748,534 | 87 | 2009-04-14T17:12:51Z | [
"python",
"datetime"
] | I can create a similar Date object in Java by [java.util.Date(milliseconds)](http://docs.oracle.com/javase/6/docs/api/java/util/Date.html). How do I create the comparable in Python?
> Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the... | Just convert it to timestamp
```
datetime.datetime.fromtimestamp(ms/1000.0)
``` |
Finding duplicate files and removing them | 748,675 | 18 | 2009-04-14T17:48:21Z | 748,687 | 8 | 2009-04-14T17:50:52Z | [
"python",
"file",
"duplicates"
] | I am writing a Python program to find and remove duplicate files from a folder.
I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.
How can I find these duplicate files and remove them? | I wrote one in Python some time ago -- you're welcome to use it.
```
import sys
import os
import hashlib
check_path = (lambda filepath, hashes, p = sys.stdout.write:
(lambda hash = hashlib.sha1 (file (filepath).read ()).hexdigest ():
((hash in hashes) and (p ('DUPLICATE FILE\n'
... |
Finding duplicate files and removing them | 748,675 | 18 | 2009-04-14T17:48:21Z | 748,879 | 14 | 2009-04-14T18:51:46Z | [
"python",
"file",
"duplicates"
] | I am writing a Python program to find and remove duplicate files from a folder.
I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.
How can I find these duplicate files and remove them? | ```
def remove_duplicates(dir):
unique = []
for filename in os.listdir(dir):
if os.path.isfile(filename):
filehash = md5.md5(file(filename).read()).hexdigest()
if filehash not in unique:
unique.append(filehash)
else:
os.remove(filename)
```
//edit:
... |
Finding duplicate files and removing them | 748,675 | 18 | 2009-04-14T17:48:21Z | 748,908 | 30 | 2009-04-14T19:00:37Z | [
"python",
"file",
"duplicates"
] | I am writing a Python program to find and remove duplicate files from a folder.
I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.
How can I find these duplicate files and remove them? | # Recursive folders version:
This version uses the file size and a hash of the contents to find duplicates.
You can pass it multiple paths, it will scan all paths recursively and report all duplicates found.
```
import sys
import os
import hashlib
def chunk_reader(fobj, chunk_size=1024):
"""Generator that reads ... |
What are the steps to convert from using libglade to GtkBuilder? (Python) | 748,872 | 5 | 2009-04-14T18:47:35Z | 749,518 | 11 | 2009-04-14T21:57:11Z | [
"python",
"pygtk",
"glade",
"gtkbuilder"
] | I have a small project that uses libglade and use the following to load the xml file:
```
self.gladefile = "sdm.glade"
self.wTree = gtk.glade.XML(self.gladefile)
self.window = self.wTree.get_widget("MainWindow")
if (self.window):
self.window.connect("destroy", gtk.main_quit)
dic = { "on_button1_clicked" : self.bu... | You need to use `gtk.Builder` instead. This class can load any number of UI files, so you need to add them manually, either as files or as strings:
```
self.uifile = "sdm.ui"
self.wTree = gtk.Builder()
self.wTree.add_from_file(self.uifile)
```
Instead of `get_widget`, just use `get_object` on the builder class:
```
... |
Django: How to use stored model instances as form choices? | 749,000 | 5 | 2009-04-14T19:24:39Z | 749,019 | 12 | 2009-04-14T19:28:43Z | [
"python",
"django",
"django-forms"
] | I have a model which is essentially just a string (django.db.models.CharField). There will only be several instances of this model stored. How could I use those values as choices in a form?
To illustrate, the model could be `BlogTopic`. I'd like to offer users the ability to choose one or several topics to subscribe t... | ```
topics = forms.ModelMultipleChoiceField(queryset=BlogTopic.objects.all())
``` |
Partial list unpack in Python | 749,070 | 30 | 2009-04-14T19:44:54Z | 749,101 | 40 | 2009-04-14T19:51:25Z | [
"python"
] | In Python, the assignment operator can unpack list or tuple into variables, like this:
```
l = (1, 2)
a, b = l # Here goes auto unpack
```
But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the list to the right, for exam... | ```
# this will result in a="length" and b="25"
a, b = "length=25".partition("=")[::2]
# this will result in a="DEFAULT_LENGTH" and b=""
a, b = "DEFAULT_LENGTH".partition("=")[::2]
``` |
Partial list unpack in Python | 749,070 | 30 | 2009-04-14T19:44:54Z | 749,340 | 41 | 2009-04-14T20:54:55Z | [
"python"
] | In Python, the assignment operator can unpack list or tuple into variables, like this:
```
l = (1, 2)
a, b = l # Here goes auto unpack
```
But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the list to the right, for exam... | This may be of no use to you unless you're using Python 3. However, for completeness, it's worth noting that the [extended tuple unpacking](http://www.python.org/dev/peps/pep-3132/) introduced there allows you to do things like:
```
>>> a, *b = "length=25".split("=")
>>> a,b
("length", ['25'])
>>> a, *b = "DEFAULT_LEN... |
Search a list of strings for any sub-string from another list | 749,342 | 17 | 2009-04-14T20:56:08Z | 749,371 | 34 | 2009-04-14T21:05:58Z | [
"python"
] | Given these 3 lists of data and a list of keywords:
```
good_data1 = ['hello, world', 'hey, world']
good_data2 = ['hey, man', 'whats up']
bad_data = ['hi, earth', 'sup, planet']
keywords = ['world', 'he']
```
I'm trying to write a simple function to check if any of the keywords exist as a substring of any word in the... | Are you looking for
```
any( k in s for k in keywords )
```
It's more compact, but might be less efficient. |
Search a list of strings for any sub-string from another list | 749,342 | 17 | 2009-04-14T20:56:08Z | 749,418 | 16 | 2009-04-14T21:23:41Z | [
"python"
] | Given these 3 lists of data and a list of keywords:
```
good_data1 = ['hello, world', 'hey, world']
good_data2 = ['hey, man', 'whats up']
bad_data = ['hi, earth', 'sup, planet']
keywords = ['world', 'he']
```
I'm trying to write a simple function to check if any of the keywords exist as a substring of any word in the... | In your example, with so few items, it doesn't really matter. But if you have a list of several thousand items, this might help.
Since you don't care which element in the list contains the keyword, you can scan the whole list once (as one string) instead of one item at the time. For that you need a join character that... |
Python: How to estimate / calculate memory footprint of data structures? | 749,625 | 11 | 2009-04-14T22:40:05Z | 749,648 | 9 | 2009-04-14T22:53:08Z | [
"python",
"memory-management"
] | What's a good way to estimate the memory footprint of an object?
Conversely, what's a good way to measure the footprint?
For example, say I have a dictionary whose values are lists of integer,float tuples:
```
d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18) ]
```
I have 4G of physical memory and woul... | [Guppy](http://guppy-pe.sourceforge.net/) has a nice memory profiler (Heapy):
```
>>> from guppy import hpy
>>> hp = hpy()
>>> hp.setrelheap() # ignore all existing objects
>>> d = {}
>>> d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18) ]
>>> hp.heap()
Partition of a set of 24 objects. Total size = 1464... |
What is the format in which Django passwords are stored in the database? | 749,682 | 23 | 2009-04-14T23:11:07Z | 749,686 | 13 | 2009-04-14T23:14:00Z | [
"python",
"django"
] | You know how django passwords are stored like this:
```
sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
```
and that is the "hashtype $salt $hash". My question is, how do they get the $hash? Is it the password and salt combined and then hashed or is something else entirely? | [According to the docs](http://docs.djangoproject.com/en/dev/topics/auth/#passwords):
> Hashtype is either sha1 (default), md5 or crypt -- the algorithm used to perform a one-way hash of the password. Salt is a random string used to salt the raw password to create the hash.
According to the code of [`set_password`](h... |
What is the format in which Django passwords are stored in the database? | 749,682 | 23 | 2009-04-14T23:11:07Z | 749,703 | 37 | 2009-04-14T23:25:06Z | [
"python",
"django"
] | You know how django passwords are stored like this:
```
sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
```
and that is the "hashtype $salt $hash". My question is, how do they get the $hash? Is it the password and salt combined and then hashed or is something else entirely? | As always, use the source:
```
# root/django/trunk/django/contrib/auth/models.py
# snip
def get_hexdigest(algorithm, salt, raw_password):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or 'crypt').
"""
raw_password, salt = sma... |
Pretty printing XML in Python | 749,796 | 262 | 2009-04-15T00:05:41Z | 749,839 | 81 | 2009-04-15T00:21:19Z | [
"python",
"xml",
"pretty-print"
] | What is the best way (or even the various ways) to pretty print xml in Python? | lxml is recent, updated, and includes a pretty print function
```
import lxml.etree as etree
x = etree.parse("filename")
print etree.tostring(x, pretty_print = True)
```
Check out the lxml tutorial:
<http://lxml.de/tutorial.html> |
Pretty printing XML in Python | 749,796 | 262 | 2009-04-15T00:05:41Z | 749,913 | 8 | 2009-04-15T00:48:22Z | [
"python",
"xml",
"pretty-print"
] | What is the best way (or even the various ways) to pretty print xml in Python? | If you're using a DOM implementation, each has their own form of pretty-printing built-in:
```
# minidom
#
document.toprettyxml()
# 4DOM
#
xml.dom.ext.PrettyPrint(document, stream)
# pxdom (or other DOM Level 3 LS-compliant imp)
#
serializer.domConfig.setParameter('format-pretty-print', True)
serializer.writeToStrin... |
Pretty printing XML in Python | 749,796 | 262 | 2009-04-15T00:05:41Z | 1,206,856 | 223 | 2009-07-30T14:12:29Z | [
"python",
"xml",
"pretty-print"
] | What is the best way (or even the various ways) to pretty print xml in Python? | ```
import xml.dom.minidom
xml = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xml.toprettyxml()
``` |
Pretty printing XML in Python | 749,796 | 262 | 2009-04-15T00:05:41Z | 3,367,423 | 44 | 2010-07-29T22:18:57Z | [
"python",
"xml",
"pretty-print"
] | What is the best way (or even the various ways) to pretty print xml in Python? | Here's my (hacky?) solution to get around the ugly text node problem.
```
uglyXml = doc.toprettyxml(indent=' ')
text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)
prettyXml = text_re.sub('>\g<1></', uglyXml)
print prettyXml
```
The above code will produce:
```
<?xml version="1.0" ?>
<issues>
<issu... |
Pretty printing XML in Python | 749,796 | 262 | 2009-04-15T00:05:41Z | 4,590,052 | 69 | 2011-01-04T01:57:31Z | [
"python",
"xml",
"pretty-print"
] | What is the best way (or even the various ways) to pretty print xml in Python? | Another solution is to borrow [this `indent` function](http://effbot.org/zone/element-lib.htm#prettyprint), for use with the ElementTree library that's built in to Python since 2.5.
Here's what that would look like:
```
from xml.etree import ElementTree
def indent(elem, level=0):
i = "\n" + level*" "
j = "\n... |
Pretty printing XML in Python | 749,796 | 262 | 2009-04-15T00:05:41Z | 5,649,263 | 16 | 2011-04-13T12:33:29Z | [
"python",
"xml",
"pretty-print"
] | What is the best way (or even the various ways) to pretty print xml in Python? | As others pointed out, lxml has a pretty printer built in.
Be aware though that by default it changes CDATA sections to normal text, which can have nasty results.
Here's a Python function that preserves the input file and only changes the indentation (notice the `strip_cdata=False`). Furthermore it makes sure the out... |
Pretty printing XML in Python | 749,796 | 262 | 2009-04-15T00:05:41Z | 10,133,365 | 9 | 2012-04-12T23:40:33Z | [
"python",
"xml",
"pretty-print"
] | What is the best way (or even the various ways) to pretty print xml in Python? | If you have `xmllint` you can spawn a subprocess and use it. `xmllint --format <file>` pretty-prints its input XML to standard output.
Note that this method uses an program external to python, which makes it sort of a hack.
```
def pretty_print_xml(xml):
proc = subprocess.Popen(
['xmllint', '--format', '/... |
How is returning the output of a function different than printing it? | 750,136 | 18 | 2009-04-15T02:53:39Z | 750,148 | 47 | 2009-04-15T02:59:11Z | [
"python",
"return"
] | In my previous [question](http://stackoverflow.com/questions/746774/basic-python-quick-question-regarding-calling-a-function), Andrew Jaffe writes:
> In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return something.
> When you create `autoparts(... | Print simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do:
```
def autoparts():
parts_dict={}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
ret... |
Emacs - tab-completion of local Python variables | 750,267 | 27 | 2009-04-15T04:04:18Z | 750,721 | 16 | 2009-04-15T08:02:33Z | [
"python",
"emacs",
"autocomplete"
] | Is there a good emacs mode that will allow tab-completion of local python variables? I set up ipython.el but it will only tab-complete things in the scope of the interpreter. I'm looking for something that will let me tab-complete tokens in the local namespace of a function or file. | M-/ runs the command dabbrev-expand . This will complete local names in any mode.
Also I bind meta f1 to hippie expand from all open buffers. This is very useful for me.
```
;; Bind hippie-expand
(global-set-key [(meta f1)] (make-hippie-expand-function
'(try-expand-dabbrev-visible
... |
Emacs - tab-completion of local Python variables | 750,267 | 27 | 2009-04-15T04:04:18Z | 750,912 | 10 | 2009-04-15T09:24:11Z | [
"python",
"emacs",
"autocomplete"
] | Is there a good emacs mode that will allow tab-completion of local python variables? I set up ipython.el but it will only tab-complete things in the scope of the interpreter. I'm looking for something that will let me tab-complete tokens in the local namespace of a function or file. | The blog post describing kind of tab completion you want can be found at
[Python code completion in Emacs](http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/).
There is a bit of installing packages, pymacs, [AutoComplete](http://www.emacswiki.org/emacs/AutoComplete), rope, ropemacs, r... |
Emacs - tab-completion of local Python variables | 750,267 | 27 | 2009-04-15T04:04:18Z | 765,390 | 13 | 2009-04-19T13:09:35Z | [
"python",
"emacs",
"autocomplete"
] | Is there a good emacs mode that will allow tab-completion of local python variables? I set up ipython.el but it will only tab-complete things in the scope of the interpreter. I'm looking for something that will let me tab-complete tokens in the local namespace of a function or file. | I use emacs-autocomplete.el (version 0.2.0) together with yasnippet. Works ok for me, although it isn't a complete auto-completion environment like eclipse+java is. But enough for a common emacs hacker like me :)
1) Download autocomplete from [here](http://www.emacswiki.org/emacs/AutoComplete) (first link) and put it ... |
How can I use Perl libraries from Python? | 750,872 | 4 | 2009-04-15T09:09:59Z | 752,483 | 8 | 2009-04-15T16:14:35Z | [
"python",
"perl",
"api"
] | I have written a bunch of Perl libraries (actually Perl classes) and I want to use some of them in my Python application. Is there a natural way to do this without using SWIG or writing Perl API for Python. I am asking for a similar way of PHP's Perl [interface](http://devzone.zend.com/node/view/id/1712). If there is n... | Personally, I would expose the Perl libs as services via XML/RPC or some other such mechanism. That way you can call them from your Python application in a very natural manner. |
Binary array in python | 751,055 | 4 | 2009-04-15T10:21:22Z | 751,080 | 7 | 2009-04-15T10:29:37Z | [
"python"
] | How to create big array in python, how efficient creating that
in C/C++:
```
byte *data = (byte*)memalloc(10000);
```
or
```
byte *data = new byte[10000];
```
in python...? | Have a look at the [array module](http://docs.python.org/library/array.html):
```
import array
array.array('B', [0] * 10000)
```
Instead of passing a list to initialize it, you can pass a generator, which is more memory efficient. |
can a method call be chained to the 'set()' built-in? (and why not?) | 751,457 | 3 | 2009-04-15T12:23:08Z | 751,497 | 20 | 2009-04-15T12:33:57Z | [
"python"
] | If I try:
```
mi_list = ['three', 'small', 'words']
mi_set = set(mi_list)
mi_set.remove('small')
print mi_set
```
I get:
```
set(['three', 'words'])
```
which is what I expect. Whereas If I try:
```
mi_list = ['three', 'small', 'words']
mi_set = set(mi_list).remove('small')
print mi_set
```
I get:
```
None
```
... | `set.remove` returns nothing (None).
Your code assigns the return value of `set.remove` to the variable `mi_set`. Therefore, mi\_set is None. |
can a method call be chained to the 'set()' built-in? (and why not?) | 751,457 | 3 | 2009-04-15T12:23:08Z | 753,944 | 8 | 2009-04-15T22:11:55Z | [
"python"
] | If I try:
```
mi_list = ['three', 'small', 'words']
mi_set = set(mi_list)
mi_set.remove('small')
print mi_set
```
I get:
```
set(['three', 'words'])
```
which is what I expect. Whereas If I try:
```
mi_list = ['three', 'small', 'words']
mi_set = set(mi_list).remove('small')
print mi_set
```
I get:
```
None
```
... | There is a general convention in python that *methods which cause [side-effects](http://en.wikipedia.org/wiki/Side%5Feffect%5F%28computer%5Fscience%29) return None*. Examples include list.sort, list.append, set.add, set.remove, dict.update, etc.
This is essentially to help you avoid bugs. Say you had a set called mi\_... |
Parse shell file output with Python | 751,557 | 4 | 2009-04-15T12:55:18Z | 751,596 | 9 | 2009-04-15T13:04:10Z | [
"python"
] | I have a file with data. The file is the output generated from a shell scripting file:
```
|a |869 |
|b |835 |
|c |0 |
|d |0 |
|e |34 |
|f |3337
```
How ... | You could do this:
```
output = {}
for line in open("myfile"):
parts = line.split('|')
output[parts[1].strip()] = parts[2].strip()
print output['a'] // prints 869
print output['f'] // prints 3337
```
Or, using the [csv](http://docs.python.org/library/csv.html) module, as suggested by [Eugene Morozov](#751587... |
Split list into smaller lists | 752,308 | 57 | 2009-04-15T15:44:40Z | 752,330 | 85 | 2009-04-15T15:49:42Z | [
"python",
"list",
"split"
] | I am looking for a way to easily split a python list in half.
So that if I have an array:
```
A = [0,1,2,3,4,5]
```
I would be able to get:
```
B = [0,1,2]
C = [3,4,5]
``` | ```
A = [1,2,3,4,5,6]
B = A[:len(A)/2]
C = A[len(A)/2:]
```
If you want a function:
```
def split_list(a_list):
half = len(a_list)/2
return a_list[:half], a_list[half:]
A = [1,2,3,4,5,6]
B, C = split_list(A)
``` |
Split list into smaller lists | 752,308 | 57 | 2009-04-15T15:44:40Z | 752,333 | 9 | 2009-04-15T15:50:08Z | [
"python",
"list",
"split"
] | I am looking for a way to easily split a python list in half.
So that if I have an array:
```
A = [0,1,2,3,4,5]
```
I would be able to get:
```
B = [0,1,2]
C = [3,4,5]
``` | `B,C=A[:len(A)/2],A[len(A)/2:]` |
Split list into smaller lists | 752,308 | 57 | 2009-04-15T15:44:40Z | 752,562 | 44 | 2009-04-15T16:30:41Z | [
"python",
"list",
"split"
] | I am looking for a way to easily split a python list in half.
So that if I have an array:
```
A = [0,1,2,3,4,5]
```
I would be able to get:
```
B = [0,1,2]
C = [3,4,5]
``` | A little more generic solution (you can specify the number of parts you want, not just split 'in half'):
**EDIT**: updated post to handle odd list lengths
**EDIT2**: update post again based on Brians informative comments
```
def split_list(alist, wanted_parts=1):
length = len(alist)
return [ alist[i*length /... |
Split list into smaller lists | 752,308 | 57 | 2009-04-15T15:44:40Z | 2,215,676 | 23 | 2010-02-07T02:30:56Z | [
"python",
"list",
"split"
] | I am looking for a way to easily split a python list in half.
So that if I have an array:
```
A = [0,1,2,3,4,5]
```
I would be able to get:
```
B = [0,1,2]
C = [3,4,5]
``` | ```
f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)]
f(A)
```
`n` - the predefined length of result arrays |
Has anyone here tried using the iSeries Python port? | 752,349 | 9 | 2009-04-15T15:52:06Z | 788,298 | 7 | 2009-04-25T05:35:36Z | [
"python",
"ibm-midrange"
] | I found <http://www.iseriespython.com/>, which is a version of Python for the iSeries apparently including some system specific data access classes. I am keen to try this out, but will have to get approval at work to do so. My questions are:
Does the port work well, or are there limits to what the interpreter can hand... | From what I have seen so far, it works pretty well. Note that I'm using iSeries Python 2.3.3. The fact that strings are natively EBCDIC can be a problem; it's definitely one of the reasons many third-party packages won't work as-is, even if they are pure Python. (In some cases they can be tweaked and massaged into work... |
Is it safe to rely on condition evaluation order in if statements? | 752,373 | 39 | 2009-04-15T15:57:19Z | 752,390 | 49 | 2009-04-15T15:59:25Z | [
"python",
"if-statement"
] | Is it bad practice to use the following format when `my_var` can be None?
```
if my_var and 'something' in my_var:
#do something
```
\*The issue is that `'something' in my_var` will throw a TypeError if my\_var is None.\*
Or should I use:
```
if my_var:
if 'something' in my_var:
#do something
```
o... | It's safe to depend on the order of conditionals ([Python reference here](http://docs.python.org/library/stdtypes.html#boolean-operations-and-or-not)), specifically because of the problem you point out - it's very useful to be able to short-circuit evaluation that could cause problems in a string of conditionals.
This... |
Is it safe to rely on condition evaluation order in if statements? | 752,373 | 39 | 2009-04-15T15:57:19Z | 752,447 | 22 | 2009-04-15T16:08:21Z | [
"python",
"if-statement"
] | Is it bad practice to use the following format when `my_var` can be None?
```
if my_var and 'something' in my_var:
#do something
```
\*The issue is that `'something' in my_var` will throw a TypeError if my\_var is None.\*
Or should I use:
```
if my_var:
if 'something' in my_var:
#do something
```
o... | Yes it is safe, it's explicitly and very clearly defined in the language reference:
> The expression `x and y` first evaluates
> `x`; if `x` is `false`, its value is
> returned; otherwise, `y` is evaluated
> and the resulting value is returned.
>
> The expression `x or y` first evaluates
> `x`; if `x` is true, its val... |
"Slicing" in Python Expressions documentation | 752,602 | 10 | 2009-04-15T16:39:42Z | 752,693 | 7 | 2009-04-15T16:56:45Z | [
"python",
"syntax",
"documentation"
] | I don't understand the following part of the Python docs:
<http://docs.python.org/reference/expressions.html#slicings>
Is this referring to list slicing ( `x=[1,2,3,4]; x[0:2]` )..? Particularly the parts referring to ellipsis..
```
slice_item ::= expression | proper_slice | ellipsis
```
> The conversion of ... | What happens is this. See <http://docs.python.org/reference/datamodel.html#types> and <http://docs.python.org/library/functions.html#slice>
> Slice objects are used to represent
> slices when extended slice syntax is
> used. This is a slice using two
> colons, or multiple slices or ellipses
> separated by commas, e.g.... |
"Slicing" in Python Expressions documentation | 752,602 | 10 | 2009-04-15T16:39:42Z | 752,895 | 11 | 2009-04-15T17:42:17Z | [
"python",
"syntax",
"documentation"
] | I don't understand the following part of the Python docs:
<http://docs.python.org/reference/expressions.html#slicings>
Is this referring to list slicing ( `x=[1,2,3,4]; x[0:2]` )..? Particularly the parts referring to ellipsis..
```
slice_item ::= expression | proper_slice | ellipsis
```
> The conversion of ... | Defining simple test class that just prints what is being passed:
```
>>> class TestGetitem(object):
... def __getitem__(self, item):
... print type(item), item
...
>>> t = TestGetitem()
```
Expression example:
```
>>> t[1]
<type 'int'> 1
>>> t[3-2]
<type 'int'> 1
>>> t['test']
<type 'str'> test
>>> t[t]
<cla... |
"Slicing" in Python Expressions documentation | 752,602 | 10 | 2009-04-15T16:39:42Z | 753,260 | 15 | 2009-04-15T19:12:07Z | [
"python",
"syntax",
"documentation"
] | I don't understand the following part of the Python docs:
<http://docs.python.org/reference/expressions.html#slicings>
Is this referring to list slicing ( `x=[1,2,3,4]; x[0:2]` )..? Particularly the parts referring to ellipsis..
```
slice_item ::= expression | proper_slice | ellipsis
```
> The conversion of ... | [Ellipsis](http://docs.python.org/dev/library/constants.html#Ellipsis) is used mainly by the [numeric python](http://numpy.scipy.org/) extension, which adds a multidementional array type. Since there are more than one dimensions, [slicing](http://numpy.scipy.org/) becomes more complex than just a start and stop index; ... |
How to work with unicode in Python | 752,998 | 14 | 2009-04-15T18:11:45Z | 753,044 | 23 | 2009-04-15T18:22:48Z | [
"python",
"string",
"unicode",
"replace",
"unicode-string"
] | I am trying to clean all of the HTML out of a string so the final output is a text file. I have some some research on the various 'converters' and am starting to lean towards creating my own dictionary for the entities and symbols and running a replace on the string. I am considering this because I want to automate the... | may be you should be doing
```
s=unicodestring.replace(u'\xa0',u'')
``` |
Strip HTML from strings in Python | 753,052 | 166 | 2009-04-15T18:24:26Z | 925,630 | 282 | 2009-05-29T11:47:41Z | [
"python",
"html"
] | ```
from mechanize import Browser
br = Browser()
br.open('http://somewebpage')
html = br.response().readlines()
for line in html:
print line
```
When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds `'<a href="whatever... | I always used this function to strip HTML tags, as it requires only the Python stdlib:
On Python 2
```
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
... |
Strip HTML from strings in Python | 753,052 | 166 | 2009-04-15T18:24:26Z | 4,869,782 | 98 | 2011-02-02T01:09:16Z | [
"python",
"html"
] | ```
from mechanize import Browser
br = Browser()
br.open('http://somewebpage')
html = br.response().readlines()
for line in html:
print line
```
When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds `'<a href="whatever... | I haven't thought much about the cases it will miss, but you can do a simple regex:
```
re.sub('<[^<]+?>', '', text)
```
For those that don't understand regex, this searches for a string `<...>`, where the inner content is made of one or more (`+`) characters that isn't a `<`. The `?` means that it will match the sma... |
Strip HTML from strings in Python | 753,052 | 166 | 2009-04-15T18:24:26Z | 7,778,368 | 22 | 2011-10-15T14:19:55Z | [
"python",
"html"
] | ```
from mechanize import Browser
br = Browser()
br.open('http://somewebpage')
html = br.response().readlines()
for line in html:
print line
```
When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds `'<a href="whatever... | I needed a way to strip tags *and* decode HTML entities to plain text. The following solution is based on Eloff's answer (which I couldn't use because it strips entities).
```
from HTMLParser import HTMLParser
import htmlentitydefs
class HTMLTextExtractor(HTMLParser):
def __init__(self):
HTMLParser.__init... |
Strip HTML from strings in Python | 753,052 | 166 | 2009-04-15T18:24:26Z | 13,703,994 | 16 | 2012-12-04T13:25:42Z | [
"python",
"html"
] | ```
from mechanize import Browser
br = Browser()
br.open('http://somewebpage')
html = br.response().readlines()
for line in html:
print line
```
When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds `'<a href="whatever... | If you need to preserve HTML entities (i.e. `&`), I added "handle\_entityref" method to [Eloff's answer](http://stackoverflow.com/a/925630/1094246).
```
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
... |
Strip HTML from strings in Python | 753,052 | 166 | 2009-04-15T18:24:26Z | 14,464,381 | 9 | 2013-01-22T17:22:29Z | [
"python",
"html"
] | ```
from mechanize import Browser
br = Browser()
br.open('http://somewebpage')
html = br.response().readlines()
for line in html:
print line
```
When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds `'<a href="whatever... | There's a simple way to this:
```
def remove_html_markup(s):
tag = False
quote = False
out = ""
for c in s:
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
tag = False
elif (c == '"' or c == "'") and tag:
... |
Strip HTML from strings in Python | 753,052 | 166 | 2009-04-15T18:24:26Z | 14,603,269 | 8 | 2013-01-30T11:47:49Z | [
"python",
"html"
] | ```
from mechanize import Browser
br = Browser()
br.open('http://somewebpage')
html = br.response().readlines()
for line in html:
print line
```
When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds `'<a href="whatever... | If you want to strip all HTML tags the easiest way I found is using BeautifulSoup:
```
from bs4 import BeautifulSoup # Or from BeautifulSoup import BeautifulSoup
def stripHtmlTags(self, htmlTxt):
if htmlTxt is None:
return None
else:
return ''.join(BeautifulSoup(htmlTxt).findAll(t... |
Strip HTML from strings in Python | 753,052 | 166 | 2009-04-15T18:24:26Z | 19,730,306 | 14 | 2013-11-01T15:51:12Z | [
"python",
"html"
] | ```
from mechanize import Browser
br = Browser()
br.open('http://somewebpage')
html = br.response().readlines()
for line in html:
print line
```
When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds `'<a href="whatever... | ## Short version!
```
import re, cgi
tag_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
# Remove well-formed tags, fixing mistakes by legitimate users
no_tags = tag_re.sub('', user_input)
# Clean up anything else by escaping
ready_for_web = cgi.escape(no_tags)
```
[Regex source: MarkupSafe](https://github.com/mitsuhiko/m... |
Programmatically generate video or animated GIF in Python? | 753,190 | 83 | 2009-04-15T18:57:14Z | 753,832 | 29 | 2009-04-15T21:34:42Z | [
"python",
"video",
"wxpython",
"animated-gif"
] | I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either... | Well, now I'm using ImageMagick. I save my frames as PNG files and then invoke ImageMagick's convert.exe from Python to create an animated GIF. The nice thing about this approach is I can specify a frame duration for each frame individually. Unfortunately this depends on ImageMagick being installed on the machine. They... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.