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 |
|---|---|---|---|---|---|---|---|---|---|
Python leaking memory while using PyQt and matplotlib | 1,249,182 | 6 | 2009-08-08T15:49:14Z | 1,249,207 | 7 | 2009-08-08T15:57:59Z | [
"python",
"memory-leaks",
"pyqt",
"matplotlib"
] | I've created a small PyQt based utility in Python that creates PNG graphs using matplotlib when a user clicks a button. Everything works well during the first few clicks, however each time an image is created, the application's memory footprint grows about 120 MB, eventually crashing Python altogether.
How can I recov... | It seems that some backends are leaking memory. Try setting your backend explicitly, e.g.
```
import matplotlib
matplotlib.use('Agg') # before import pylab
import pylab
``` |
Removing all non-numeric characters from string in Python | 1,249,388 | 63 | 2009-08-08T17:13:01Z | 1,249,398 | 48 | 2009-08-08T17:16:55Z | [
"python",
"numbers"
] | How do we remove all non-numeric characters from a string in Python? | Not sure if this is the most efficient way, but:
```
>>> ''.join(c for c in "abc123def456" if c.isdigit())
'123456'
```
The `''.join` part means to combine all the resulting characters together without any characters in between. Then the rest of it is a list comprehension, where (as you can probably guess) we only ta... |
Removing all non-numeric characters from string in Python | 1,249,388 | 63 | 2009-08-08T17:13:01Z | 1,249,424 | 118 | 2009-08-08T17:25:21Z | [
"python",
"numbers"
] | How do we remove all non-numeric characters from a string in Python? | ```
>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'
``` |
Removing all non-numeric characters from string in Python | 1,249,388 | 63 | 2009-08-08T17:13:01Z | 1,387,394 | 10 | 2009-09-07T03:01:27Z | [
"python",
"numbers"
] | How do we remove all non-numeric characters from a string in Python? | This should work for strings and unicode objects:
```
# python <3.0
def only_numerics(seq):
return filter(type(seq).isdigit, seq)
# python â¥3.0
def only_numerics(seq):
seq_type= type(seq)
return seq_type().join(filter(seq_type.isdigit, seq))
``` |
`cat filename | grep -B 5 -C 5 foo` | 1,249,412 | 2 | 2009-08-08T17:22:35Z | 1,249,428 | 7 | 2009-08-08T17:27:04Z | [
"python",
"grep"
] | ```
for filename in os.listdir("."):
for line in open(filename).xreadlines():
if "foo" in line:
print line
```
So this is a simple python equivalent of `cat filename | grep foo`. However, I would like the equivalent of `cat filename | grep -B 5 -C 5 foo`, how should the above code be modified? | Simplest way is:
```
for filename in os.listdir("."):
lines = open(filename).readlines()
for i, line in enumerate(lines):
if "foo" in line:
for x in lines[i-5 : i+6]:
print x,
```
add line numbers, breaks between blocks, etc, to taste;-).
In the extremely unlikely case tha... |
Simple python/Regex problem: Removing all new lines from a file | 1,249,670 | 14 | 2009-08-08T19:15:59Z | 1,249,740 | 23 | 2009-08-08T19:54:28Z | [
"python",
"regex"
] | I'm becoming acquainted with python and am creating problems in order to help myself learn the ins and outs of the language. My next problem comes as follows:
I have copied and pasted a huge slew of text from the internet, but the copy and paste added several new lines to break up the huge string. I wish to programati... | The two main alternatives: read everything in as a single string and remove newlines:
```
clean = open('thefile.txt').read().replace('\n', '')
```
or, read line by line, removing the newline that ends each line, and join it up again:
```
clean = ''.join(l[:-1] for l in open('thefile.txt'))
```
The former alternativ... |
Is there a string-collapse library function in python? | 1,249,786 | 4 | 2009-08-08T20:18:54Z | 1,249,850 | 12 | 2009-08-08T20:43:34Z | [
"python",
"string",
"line-breaks"
] | Is there a cross-platform library function that would collapse a multiline string into a single-line string with no repeating spaces?
I've come up with some snip below, but I wonder if there is a standard function which I could just import which is perhaps even optimized in C?
```
def collapse(input):
import re
... | The built-in `string.split()` method will split on runs of whitespace, so you can use that and then join the resulting list using spaces, like this:
```
' '.join(my_string.split())
```
Here's a complete test script:
```
TEST = """This
is a test\twith a
mix of\ttabs, newlines and repeating
whitespace"""
... |
AttributeError: 'module' object has no attribute | 1,250,103 | 75 | 2009-08-08T23:12:20Z | 1,250,119 | 20 | 2009-08-08T23:19:41Z | [
"python",
"attributeerror"
] | I have two python modules:
a.py
```
import b
def hello():
print "hello"
print "a.py"
print hello()
print b.hi()
```
b.py
```
import a
def hi():
print "hi"
```
When I run `a.py`, I get:
```
AttributeError: 'module' object has no attribute 'hi'
```
What does the error mean? How do I fix it? | The problem is the circular dependency between the modules. `a` imports `b` and `b` imports `a`. But one of them needs to be loaded first - in this case python ends up initializing module `a` before `b` and `b.hi()` doesn't exist yet when you try to access it in `a`. |
AttributeError: 'module' object has no attribute | 1,250,103 | 75 | 2009-08-08T23:12:20Z | 1,250,135 | 83 | 2009-08-08T23:27:29Z | [
"python",
"attributeerror"
] | I have two python modules:
a.py
```
import b
def hello():
print "hello"
print "a.py"
print hello()
print b.hi()
```
b.py
```
import a
def hi():
print "hi"
```
When I run `a.py`, I get:
```
AttributeError: 'module' object has no attribute 'hi'
```
What does the error mean? How do I fix it? | You have mutual top-level imports, which is almost always a bad idea.
If you really must have mutual imports in Python, the way to do it is to import them within a function:
```
# In b.py:
def cause_a_to_do_something():
import a
a.do_something()
```
Now a.py can safely do `import b` without causing problems.... |
AttributeError: 'module' object has no attribute | 1,250,103 | 75 | 2009-08-08T23:12:20Z | 3,124,164 | 39 | 2010-06-26T14:18:21Z | [
"python",
"attributeerror"
] | I have two python modules:
a.py
```
import b
def hello():
print "hello"
print "a.py"
print hello()
print b.hi()
```
b.py
```
import a
def hi():
print "hi"
```
When I run `a.py`, I get:
```
AttributeError: 'module' object has no attribute 'hi'
```
What does the error mean? How do I fix it? | I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called `commands` which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the s... |
AttributeError: 'module' object has no attribute | 1,250,103 | 75 | 2009-08-08T23:12:20Z | 29,687,721 | 8 | 2015-04-16T23:32:08Z | [
"python",
"attributeerror"
] | I have two python modules:
a.py
```
import b
def hello():
print "hello"
print "a.py"
print hello()
print b.hi()
```
b.py
```
import a
def hi():
print "hi"
```
When I run `a.py`, I get:
```
AttributeError: 'module' object has no attribute 'hi'
```
What does the error mean? How do I fix it? | I got this error by referencing an enum which was imported in a wrong way, e.g.:
```
from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member
```
Correct import:
```
from package.MyEnumClass import MyEnumClass
```
Hope that helps someone |
What is the importance of an IDE when programming in Python? | 1,250,295 | 5 | 2009-08-09T01:02:37Z | 1,250,375 | 9 | 2009-08-09T01:50:58Z | [
"python",
"ide"
] | I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even *possible* to program outside of such a tool.
However, much of the documenta... | IDEs arent *very* useful in Python; powerful editors such as Emacs and Vim seem very popular among Python programmers.
This may confuse e.g. Java programmers, because in Java each file generally requires boilerplate code, such as a `package` statement, getters and setters.
Python is much more lightweight in comparison.... |
Creating alternative login to Google Users for Google app engine | 1,250,437 | 4 | 2009-08-09T02:46:19Z | 1,250,451 | 8 | 2009-08-09T02:53:37Z | [
"python",
"google-app-engine",
"model-view-controller",
"gae-datastore"
] | How does one handle logging in and out/creating users, without using Google Users? I'd like a few more options then just email and password. Is it just a case of making a user model with the fields I need? Is that secure enough?
Alternatively, is there a way to get the user to log in using the Google ID, but without b... | I recommend using OpenID, see [here](http://googlecode.blogspot.com/2009/07/google-apps-openid-identity-hub-for.html) for more -- just like Stack Overflow does!-) |
Decompressing a .bz2 file in Python | 1,250,688 | 4 | 2009-08-09T05:01:42Z | 1,250,700 | 14 | 2009-08-09T05:06:29Z | [
"python",
"decompression",
"decompress"
] | So, this is a seemingly simple question, but I'm apparently very very dull. I have a little script that downloads all the .bz2 files from a webpage, but for some reason the decompressing of that file is giving me a MAJOR headache.
I'm quite a Python newbie, so the answer is probably quite obvious, please help me.
In ... | You're opening and reading the compressed file as if it was a textfile made up of lines. DON'T! It's NOT.
```
uncompressedData = bz2.BZ2File(zipFile).read()
```
seems to be closer to what you're angling for.
**Edit**: the OP has shown a few more things he's tried (though I don't see any notes about having tried the ... |
Decompressing a .bz2 file in Python | 1,250,688 | 4 | 2009-08-09T05:01:42Z | 1,250,948 | 8 | 2009-08-09T08:23:04Z | [
"python",
"decompression",
"decompress"
] | So, this is a seemingly simple question, but I'm apparently very very dull. I have a little script that downloads all the .bz2 files from a webpage, but for some reason the decompressing of that file is giving me a MAJOR headache.
I'm quite a Python newbie, so the answer is probably quite obvious, please help me.
In ... | > openZip = open(zipFile, "r")
If you're running on Windows, you may want to do say **openZip = open(zipFile, "rb")** here since the file is likely to contain CR/LF combinations, and you don't want them to be translated.
> newLine = openZip.readline()
As Alex pointed out, this is very wrong, as the concept of "lines... |
Python Class vs. Module Attributes | 1,250,779 | 12 | 2009-08-09T06:04:50Z | 1,251,929 | 7 | 2009-08-09T18:29:25Z | [
"python",
"attributes",
"class-design",
"module"
] | I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?
The problem I have... | #4:
I *never* use class attributes to initialize default instance attributes (the ones you normally put in `__init__`). For example:
```
class Obj(object):
def __init__(self):
self.users = 0
```
and never:
```
class Obj(object):
users = 0
```
Why? Because it's inconsistent: it doesn't do what you wa... |
Read from socket: Is it guaranteed to at least get x bytes? | 1,251,392 | 4 | 2009-08-09T13:35:11Z | 1,251,406 | 9 | 2009-08-09T13:45:38Z | [
"python",
"sockets",
"network-protocols"
] | I have a rare bug that seems to occur reading a socket.
It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than this.
As I learned from pipe-programming, there I always get at least 512 bytes as long as the sender provides enough data.
Also my sender does at least t... | As far as I know, this behaviour is perfectly reasonable. Sockets may, and probably **will** fragment your data as they transmit it. You should be prepared to handle such cases by applying appropriate buffering techniques.
On other hand, if you are transmitting the data on the localhost and you are indeed getting only... |
Read from socket: Is it guaranteed to at least get x bytes? | 1,251,392 | 4 | 2009-08-09T13:35:11Z | 1,251,512 | 13 | 2009-08-09T14:43:25Z | [
"python",
"sockets",
"network-protocols"
] | I have a rare bug that seems to occur reading a socket.
It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than this.
As I learned from pipe-programming, there I always get at least 512 bytes as long as the sender provides enough data.
Also my sender does at least t... | I assume you're using TCP. TCP is a stream based protocol with no idea of packets or message boundaries.
This means when you do a read you may get less bytes than you request. If your data is 128k for example you may only get 24k on your first read requiring you to read again to get the rest of the data.
For an examp... |
How to enumerate an object's properties in Python? | 1,251,692 | 66 | 2009-08-09T16:33:02Z | 1,251,702 | 77 | 2009-08-09T16:37:09Z | [
"python",
"reflection",
"properties"
] | I C# we do it through reflection. In Javascript it is simple as:
```
for(var propertyName in objectName)
var currentPropertyValue = objectName[propertyName];
```
How to do it in Python? | ```
for property, value in vars(theObject).iteritems():
print property, ": ", value
```
Be aware that in some rare cases there's a `__slots__` property, such classes often have no `__dict__`. |
How to enumerate an object's properties in Python? | 1,251,692 | 66 | 2009-08-09T16:33:02Z | 1,251,704 | 27 | 2009-08-09T16:37:48Z | [
"python",
"reflection",
"properties"
] | I C# we do it through reflection. In Javascript it is simple as:
```
for(var propertyName in objectName)
var currentPropertyValue = objectName[propertyName];
```
How to do it in Python? | [`dir()`](http://docs.python.org/library/functions.html#dir) is the simple way. See here:
[Guide To Python Introspection](http://www.ibm.com/developerworks/library/l-pyint.html) |
How to enumerate an object's properties in Python? | 1,251,692 | 66 | 2009-08-09T16:33:02Z | 1,251,705 | 10 | 2009-08-09T16:37:50Z | [
"python",
"reflection",
"properties"
] | I C# we do it through reflection. In Javascript it is simple as:
```
for(var propertyName in objectName)
var currentPropertyValue = objectName[propertyName];
```
How to do it in Python? | The `__dict__` property of the object is a dictionary of all its other defined properties. Note that Python classes can override [**getattr**](http://docs.python.org/reference/datamodel.html#object.__getattr__)
and make things that look like properties but are not in`__dict__`. There's also the builtin functions `vars(... |
How to enumerate an object's properties in Python? | 1,251,692 | 66 | 2009-08-09T16:33:02Z | 1,251,789 | 54 | 2009-08-09T17:23:08Z | [
"python",
"reflection",
"properties"
] | I C# we do it through reflection. In Javascript it is simple as:
```
for(var propertyName in objectName)
var currentPropertyValue = objectName[propertyName];
```
How to do it in Python? | See [`inspect.getmembers(object[, predicate])`](http://docs.python.org/library/inspect.html#inspect.getmembers).
> Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.... |
Printing Python version in output | 1,252,163 | 151 | 2009-08-09T20:15:39Z | 1,252,164 | 189 | 2009-08-09T20:16:47Z | [
"python"
] | How can I print version number for the current Python installation in the output? | Try
```
import sys
print(sys.version)
```
This prints the full version information string. If you only want the python version number, then [Bastien Léonard's solution](http://stackoverflow.com/questions/1252163/printing-python-version-in-output/1252175#1252175) is the best. You might want to examine the full string... |
Printing Python version in output | 1,252,163 | 151 | 2009-08-09T20:15:39Z | 1,252,165 | 21 | 2009-08-09T20:17:32Z | [
"python"
] | How can I print version number for the current Python installation in the output? | ```
import platform
print(platform.python_version())
```
or
```
import sys
print("The Python version is %s.%s.%s" % sys.version_info[:3])
```
Edit: I had totally missed the platform.python\_version() medthod. |
Printing Python version in output | 1,252,163 | 151 | 2009-08-09T20:15:39Z | 1,252,175 | 73 | 2009-08-09T20:21:00Z | [
"python"
] | How can I print version number for the current Python installation in the output? | ```
>>> import platform
>>> platform.python_version()
'2.6.2'
``` |
Printing Python version in output | 1,252,163 | 151 | 2009-08-09T20:15:39Z | 11,734,305 | 20 | 2012-07-31T06:24:33Z | [
"python"
] | How can I print version number for the current Python installation in the output? | Try
```
python --version
```
or
```
python -V
```
This will return a current python version in terminal. |
Printing Python version in output | 1,252,163 | 151 | 2009-08-09T20:15:39Z | 17,145,598 | 10 | 2013-06-17T10:42:34Z | [
"python"
] | How can I print version number for the current Python installation in the output? | ```
import sys
```
expanded version
```
sys.version_info
sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0)
```
specific
```
maj_ver = sys.version_info.major
repr(maj_ver)
'3'
```
or
```
print(sys.version_info.major)
'3'
```
or
```
version = ".".join(map(str, sys.version_info[:3]))... |
How to check null value for UserProperty in Google App Engine | 1,252,196 | 5 | 2009-08-09T20:29:00Z | 1,252,322 | 13 | 2009-08-09T21:21:05Z | [
"python",
"google-app-engine",
"gae-datastore"
] | In Google App Engine, datastore modelling, I would like to ask how can I check for null value of a property with class UserProperty?
for example:
I have this code:
```
class Entry(db.Model):
title = db.StringProperty()
description = db.StringProperty()
author = db.UserProperty()
editor = db.UserProperty()
cr... | ```
query = db.GqlQuery("SELECT * FROM Entry WHERE editor > :1",None)
```
However, you can't `ORDER BY` one column *and* have an inequality condition on another column: that's a well-known GAE limitation and has nothing to do with the property being a UserProperty nor with the inequality check you're doing being with ... |
PIL Image.resize() not resizing the picture | 1,252,218 | 19 | 2009-08-09T20:36:35Z | 1,252,229 | 56 | 2009-08-09T20:39:53Z | [
"python",
"django",
"resize",
"python-imaging-library"
] | I have some strange problem with PIL not resizing the image.
```
def handle_uploaded_image(i, u):
# resize image
from PIL import Image
img = Image.open(i)
if img.mode not in ('L', 'RGB'):
img = img.convert('RGB')
width, height = img.size
if width == height:
img.thumbnail(settings.T... | `resize()` returns a resized copy of an image. It doesn't modify the original. The correct way to use it is:
```
img = img.resize((150, newheight), image.ANTIALIAS)
```
[source](http://effbot.org/imagingbook/image.htm)
I think what you are looking for is the ImageOps.fit function. From PIL [docs](http://effbot.org/i... |
Django + Jquery, expanding AJAX div | 1,252,275 | 4 | 2009-08-09T20:58:47Z | 1,252,311 | 12 | 2009-08-09T21:13:59Z | [
"jquery",
"python",
"django"
] | How can I, when a user clicks a link, open a div right underneath the link which loads it's content via AJAX?
Thanks for the help; I cannot find out how to. Just statically filling the div on the server side while loading the page works fine, but it's too much content for that.
I'm kind of looking for a specific Djan... | [jQuery.load](http://docs.jquery.com/Ajax/load) does exactly that:
```
$("div#my-container").load("/url/to/content/ #content-id")
```
this fetches the content from `/url/to/content/`, filters it by `#content-id` and injects the result into `div#my-container`.
edit: there's really nothing Django-specific about this, ... |
Is there an object unique identifier in Python | 1,252,357 | 31 | 2009-08-09T21:40:30Z | 1,252,364 | 49 | 2009-08-09T21:42:32Z | [
"python"
] | This would be similar to the java.lang.Object.hashcode() method.
I need to store objects I have no control over in a set, and make sure that only if two objects are actually the same object (not contain the same values) will the values be overwritten. | ```
id(x)
```
will do the trick for you. But I'm curious, what's wrong about the set of objects (which does combine objects by value)?
For your particular problem I would probably keep the set of ids or of wrapper objects. A wrapper object will contain one reference and compare by `x==y` <==> `x.ref is y.ref`.
It's ... |
Is there an object unique identifier in Python | 1,252,357 | 31 | 2009-08-09T21:40:30Z | 1,252,369 | 12 | 2009-08-09T21:43:35Z | [
"python"
] | This would be similar to the java.lang.Object.hashcode() method.
I need to store objects I have no control over in a set, and make sure that only if two objects are actually the same object (not contain the same values) will the values be overwritten. | That's what "`is`" is for.
Instead of testing "`if a == b`", which tests for the same value,
test "`if a is b`", which will test for the same identifier. |
sort dictionary by another dictionary | 1,252,481 | 2 | 2009-08-09T22:26:25Z | 1,252,500 | 7 | 2009-08-09T22:34:31Z | [
"python",
"sorting",
"dictionary"
] | I've been having a problem with making sorted lists from dictionaries.
I have this list
```
list = [
d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7', 'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'},
d = {'file_name':'thatfile.flt', 'item_name':'teapot', 'item_height'... | The first code box has invalid Python syntax (I suspect the `d =` parts are extraneous...?) as well as unwisely trampling on the built-in name `list`.
Anyway, given for example:
```
d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7',
'item_width':'10.5', 'item_depth':'2.2', 'texture_file': ... |
Which path module or class do Python folks use instead of os.path? | 1,252,639 | 5 | 2009-08-10T00:03:40Z | 1,252,644 | 11 | 2009-08-10T00:10:48Z | [
"python",
"path"
] | Just wondering how many people use a path module in Python such as Jason Orendorff's one, instead of using `os.path` for joining and splitting paths? Have you used:
* [Jason's path module](http://wiki.python.org/moin/PathModule) (updated for PEP 355)
* [Mike Orr's Unipath](http://sluggo.scrapping.cc/python/unipath/Uni... | I can pick up a Python program and interpret the current standard method without hesitation - it's explicit and there's no ambiguity:
```
os.path.join(build_dir, os.path.basename(source_file))
```
Python's dynamic typing makes the first method rather difficult to comprehend when reading:
```
build_dir / path(source_... |
Distributing my python scripts as jars with jython? | 1,252,965 | 50 | 2009-08-10T03:11:51Z | 1,255,113 | 57 | 2009-08-10T14:12:55Z | [
"python",
"jython",
"distribution",
"executable-jar"
] | I have been a python programmer for almost 2 years and I am used to writing small scripts to automate some repetitive tasks I had to do at office. Now, apparently my colleagues noticed this and they want those scripts too.
Some of them have macs, some windows, I made these on windows. I investigated the possibility of... | The best current techniques for distributing your Python files in a jar are detailed in this article on Jython's wiki: <http://wiki.python.org/jython/JythonFaq/DistributingJythonScripts>
For your case, I think you would want to take the jython.jar file that you get when you install Jython and zip the Jython Lib direct... |
Why does subprocess.Popen() with shell=True work differently on Linux vs Windows? | 1,253,122 | 19 | 2009-08-10T04:39:58Z | 1,254,322 | 14 | 2009-08-10T11:09:49Z | [
"python",
"shell",
"subprocess",
"popen"
] | When using `subprocess.Popen(args, shell=True)` to run "`gcc --version`" (just as an example), on Windows we get this:
```
>>> from subprocess import Popen
>>> Popen(['gcc', '--version'], shell=True)
gcc (GCC) 3.4.5 (mingw-vista special r3) ...
```
So it's nicely printing out the version as I expect. But on Linux we ... | Actually on Windows, it does use `cmd.exe` when `shell=True` - it prepends `cmd.exe /c` (it actually looks up the `COMSPEC` environment variable but defaults to `cmd.exe` if not present) to the shell arguments. (On Windows 95/98 it uses the intermediate `w9xpopen` program to actually launch the command).
So the stran... |
Is there an easy way to pickle a python function (or otherwise serialize its code)? | 1,253,528 | 68 | 2009-08-10T07:25:47Z | 1,253,540 | 9 | 2009-08-10T07:29:42Z | [
"python",
"function",
"pickle"
] | I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?
I would ideally like to have a pair of functions similar to these:
```
def transmit(func):... | The most simple way is probably `inspect.getsource(object)` (see the [inspect module](http://docs.python.org/library/inspect.html#retrieving-source-code)) which returns a String with the source code for a function or a method. |
Is there an easy way to pickle a python function (or otherwise serialize its code)? | 1,253,528 | 68 | 2009-08-10T07:25:47Z | 1,253,579 | 13 | 2009-08-10T07:45:33Z | [
"python",
"function",
"pickle"
] | I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?
I would ideally like to have a pair of functions similar to these:
```
def transmit(func):... | [Pyro](http://pythonhosted.org/Pyro4/) is able to [do this for you](http://packages.python.org/Pyro/7-features.html#mobile). |
Is there an easy way to pickle a python function (or otherwise serialize its code)? | 1,253,528 | 68 | 2009-08-10T07:25:47Z | 1,253,813 | 91 | 2009-08-10T08:58:22Z | [
"python",
"function",
"pickle"
] | I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?
I would ideally like to have a pair of functions similar to these:
```
def transmit(func):... | You could serialise the function bytecode and then reconstruct it on the caller. The [marshal](https://docs.python.org/3/library/marshal.html) module can be used to serialise code objects, which can then be reassembled into a function. ie:
```
import marshal
def foo(x): return x*x
code_string = marshal.dumps(foo.func_... |
Is there an easy way to pickle a python function (or otherwise serialize its code)? | 1,253,528 | 68 | 2009-08-10T07:25:47Z | 20,417,344 | 15 | 2013-12-06T06:20:22Z | [
"python",
"function",
"pickle"
] | I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?
I would ideally like to have a pair of functions similar to these:
```
def transmit(func):... | Check out [Dill](https://pypi.python.org/pypi/dill), which extends Python's pickle library to support a greater variety of types, including functions:
```
>>> import dill as pickle
>>> def f(x): return x + 1
...
>>> g = pickle.dumps(f)
>>> f(1)
2
>>> pickle.loads(g)(1)
2
```
It also supports references to objects in ... |
Suggestion Needed - Networking in Python - A good idea? | 1,253,905 | 4 | 2009-08-10T09:26:22Z | 1,255,979 | 9 | 2009-08-10T16:52:04Z | [
"python",
"network-programming"
] | I am considering programming the network related features of my application in Python instead of the C/C++ API. The intended use of networking is to pass text messages between two instances of my application, similar to a game passing player positions as often as possible over the network.
Although the python socket m... | Check out [Twisted](http://twistedmatrix.com/trac/), a Python engine for Networking. Has built-in support for TCP, UDP, SSL/TLS, multicast, Unix sockets, a large number of protocols (including HTTP, NNTP, IMAP, SSH, IRC, FTP, and others) |
Has anyone succeeded in using Google App Engine with Python version 2.6? | 1,254,028 | 9 | 2009-08-10T09:58:39Z | 1,254,047 | 11 | 2009-08-10T10:04:45Z | [
"python",
"google-app-engine"
] | Since Python 2.6 is backward compatible to 2.52 , did anyone succeeded in using it with Google app Engine ( which supports 2.52 officially ).
I know i should try it myself. But i am a python and web-apps new bee and for me installation and configuration is the hardest part while getting started with something new in t... | I suppose logging module crashes if you try to start the dev environment. See [the issue and a workaround](http://code.google.com/p/googleappengine/issues/detail?id=1159#c7).
After doing that change my code worked in 2.6 without any problems. I suggest using 2.5.x though so there are no other incompatibilities introdu... |
Avoid program exit on I/O error | 1,254,292 | 3 | 2009-08-10T11:05:10Z | 1,254,324 | 7 | 2009-08-10T11:10:03Z | [
"python",
"shutil"
] | I have a Python script using shutil.copy2 extensively. Since I use it to copy files over the network, I get too frequent I/O errors, which lead to the abortion of my program's execution:
```
Traceback (most recent call last):
File "run_model.py", line 46, in <module>
main()
File "run_model.py", line 41, in mai... | Which block is giving the error? Just wrap a [try/except](http://docs.python.org/tutorial/errors.html) around it:
```
def check_file(file, size=0):
try:
if not os.path.exists(file):
return False
if (size != 0 and os.path.getsize(file) != size):
return False
return Tr... |
Reimport a module in python while interactive | 1,254,370 | 148 | 2009-08-10T11:24:17Z | 1,254,379 | 168 | 2009-08-10T11:29:12Z | [
"python"
] | I know it can be done, but I never remember how.
How can you reimport a module in python?
The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fixed module without quitting python. How can I do it ? | This should work:
```
reload(my.module)
```
From the [Python docs](http://docs.python.org/library/functions.html#reload)
> Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an ex... |
Reimport a module in python while interactive | 1,254,370 | 148 | 2009-08-10T11:24:17Z | 14,390,676 | 67 | 2013-01-18T00:35:29Z | [
"python"
] | I know it can be done, but I never remember how.
How can you reimport a module in python?
The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fixed module without quitting python. How can I do it ? | In python 3, `reload` is no longer a built in function.
If you are using python 3.4+ you should use [`reload`](https://docs.python.org/3/library/importlib.html#importlib.reload) from the [`importlib`](https://docs.python.org/3/library/importlib.html) library instead.
If you are using python 3.2 or 3.3 you should:
``... |
Reimport a module in python while interactive | 1,254,370 | 148 | 2009-08-10T11:24:17Z | 23,901,170 | 28 | 2014-05-28T00:39:22Z | [
"python"
] | I know it can be done, but I never remember how.
How can you reimport a module in python?
The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fixed module without quitting python. How can I do it ? | Actually, in Python 3 the module `imp` is marked as DEPRECATED. Well, at least that's true for 3.4.
Instead the `reload` function from the `importlib` module should be used:
<https://docs.python.org/3/library/importlib.html#importlib.reload>
But be aware that this library had some API-changes with the last two minor... |
Fastest way to convert a dict's keys & values from `unicode` to `str`? | 1,254,454 | 45 | 2009-08-10T11:51:17Z | 1,254,499 | 102 | 2009-08-10T12:03:54Z | [
"python",
"casting",
"types"
] | I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys & "string" values are `unicode`, but the layer they're being passed onto only accepts `str`.
This is going to be called often, so I'd like to know what... | ```
DATA = { u'spam': u'eggs', u'foo': frozenset([u'Gah!']), u'bar': { u'baz': 97 },
u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])]}
def convert(data):
if isinstance(data, basestring):
return str(data)
elif isinstance(data, collections.Mapping):
return dict(map(co... |
Fastest way to convert a dict's keys & values from `unicode` to `str`? | 1,254,454 | 45 | 2009-08-10T11:51:17Z | 6,728,427 | 10 | 2011-07-18T03:39:39Z | [
"python",
"casting",
"types"
] | I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys & "string" values are `unicode`, but the layer they're being passed onto only accepts `str`.
This is going to be called often, so I'd like to know what... | If you wanted to do this inline and didn't need recursive descent, this might work:
```
DATA = { u'spam': u'eggs', u'foo': True, u'bar': { u'baz': 97 } }
print DATA
# "{ u'spam': u'eggs', u'foo': True, u'bar': { u'baz': 97 } }"
STRING_DATA = dict([(str(k), v) for k, v in data.items()])
print STRING_DATA
# "{ 'spam': ... |
Fastest way to convert a dict's keys & values from `unicode` to `str`? | 1,254,454 | 45 | 2009-08-10T11:51:17Z | 7,027,514 | 13 | 2011-08-11T14:18:22Z | [
"python",
"casting",
"types"
] | I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys & "string" values are `unicode`, but the layer they're being passed onto only accepts `str`.
This is going to be called often, so I'd like to know what... | I know I'm late on this one:
```
def convert_keys_to_string(dictionary):
"""Recursively converts dictionary keys to strings."""
if not isinstance(dictionary, dict):
return dictionary
return dict((str(k), convert_keys_to_string(v))
for k, v in dictionary.items())
``` |
Can Python's optparse display the default value of an option? | 1,254,469 | 38 | 2009-08-10T11:55:02Z | 1,254,491 | 50 | 2009-08-10T12:01:33Z | [
"python",
"optparse"
] | Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help? | Try using the `%default` string placeholder:
```
# This example taken from http://docs.python.org/library/optparse.html#generating-help
parser.add_option("-m", "--mode",
default="intermediate",
help="interaction mode: novice, intermediate, "
"or expert [defaul... |
Can Python's optparse display the default value of an option? | 1,254,469 | 38 | 2009-08-10T11:55:02Z | 1,254,500 | 7 | 2009-08-10T12:04:04Z | [
"python",
"optparse"
] | Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help? | And if you need programmatic access to the default values, you can get to them via the `defaults` attribute of the parser (it's a dict) |
Can Python's optparse display the default value of an option? | 1,254,469 | 38 | 2009-08-10T11:55:02Z | 11,906,371 | 7 | 2012-08-10T17:16:52Z | [
"python",
"optparse"
] | Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help? | And if you want to add default values automatically to all options that you have specified, you can do the following:
```
for option in parser.option_list:
if option.default != ("NO", "DEFAULT"):
option.help += (" " if option.help else "") + "[default: %default]"
``` |
Why don't Django and CherryPy support HTTP verb-based dispatch natively? | 1,254,629 | 10 | 2009-08-10T12:39:18Z | 1,255,171 | 12 | 2009-08-10T14:22:15Z | [
"python",
"django",
"rest",
"cherrypy",
"web-frameworks"
] | It's not the same to POST to an URL than to GET it, DELETE it or PUT it. These actions are fundamentally different. However, Django seems to ignore them in its dispatch mechanism. Basically, one is forced to either ignore HTTP verbs completely or do this on every view:
```
def my_view(request, arg1, arg2):
if requ... | I can't speak for Django, but in CherryPy, you can have one function per HTTP verb with a single config entry:
```
request.dispatch = cherrypy.dispatch.MethodDispatcher()
```
However, I have seen some situations where that's not desirable.
One example would be a hard redirect regardless of verb.
Another case is whe... |
Why don't Django and CherryPy support HTTP verb-based dispatch natively? | 1,254,629 | 10 | 2009-08-10T12:39:18Z | 15,728,522 | 7 | 2013-03-31T10:35:44Z | [
"python",
"django",
"rest",
"cherrypy",
"web-frameworks"
] | It's not the same to POST to an URL than to GET it, DELETE it or PUT it. These actions are fundamentally different. However, Django seems to ignore them in its dispatch mechanism. Basically, one is forced to either ignore HTTP verbs completely or do this on every view:
```
def my_view(request, arg1, arg2):
if requ... | Came across this from Google, and thought of updating.
# Django
Just FYI, This is now supported in Django as class based views. You can extend the generic class `View` and add methods like `get()`, `post()`, `put()` etc. E.g. -
```
from django.http import HttpResponse
from django.views.generic import View
class MyV... |
Non-editable text box in wxPython | 1,254,819 | 5 | 2009-08-10T13:16:03Z | 1,254,881 | 7 | 2009-08-10T13:29:01Z | [
"python",
"textbox",
"wxpython",
"wx"
] | How to create a non-editable text box with no cursor in wxPython to dump text in? | `wx.StaticText`
You could also use a regular TextCtrl with the style `TE_READONLY` but that shows a cursor and the text looks editable, but it isn't. |
How do I validate XML document using RELAX NG schema in Python? | 1,254,919 | 7 | 2009-08-10T13:33:51Z | 1,254,992 | 15 | 2009-08-10T13:46:26Z | [
"python",
"xml",
"relaxng"
] | How do I validate XML document via compact RELAX NG schema in Python? | How about using [lxml](http://codespeak.net/lxml/validation.html#relaxng)?
From the docs:
```
>>> f = StringIO('''\
... <element name="a" xmlns="http://relaxng.org/ns/structure/1.0">
... <zeroOrMore>
... <element name="b">
... <text />
... </element>
... </zeroOrMore>
... </element>
... ''')
>>> relax... |
Finding Functions Defined in a with: Block | 1,255,914 | 9 | 2009-08-10T16:38:03Z | 1,256,018 | 11 | 2009-08-10T17:02:58Z | [
"python",
"scope",
"with-statement",
"contextmanager"
] | Here's some code from [Richard Jones' Blog](http://www.mechanicalcat.net/richard/log/Python/Something%5FI%5Fm%5Fworking%5Fon.3):
```
with gui.vertical:
text = gui.label('hello!')
items = gui.selection(['one', 'two', 'three'])
with gui.button('click me!'):
def on_click():
text.value = it... | Here's one way:
```
from __future__ import with_statement
import inspect
class button(object):
def __enter__(self):
# keep track of all that's already defined BEFORE the `with`
f = inspect.currentframe(1)
self.mustignore = dict(f.f_locals)
def __exit__(self, exc_type, exc_value, traceback):
f = i... |
How do you dynamically hide form fields in Django? | 1,255,976 | 13 | 2009-08-10T16:51:04Z | 1,256,705 | 14 | 2009-08-10T19:18:53Z | [
"python",
"django",
"django-forms"
] | I am making a profile form in Django. There are a lot of optional extra profile fields but I would only like to show two at a time. How do I hide or remove the fields I do not want to show dynamically?
Here is what I have so far:
```
class UserProfileForm(forms.ModelForm):
extra_fields = ('field1', 'field2', 'fie... | I think I found my answer.
First I tried:
```
field.widget = field.hidden_widget
```
which didn't work.
The correct way happens to be:
```
field.widget = field.hidden_widget()
``` |
Django - Getting last object created, simultaneous filters | 1,256,190 | 21 | 2009-08-10T17:35:15Z | 1,256,325 | 31 | 2009-08-10T18:04:21Z | [
"python",
"django",
"filter",
"django-views"
] | Apologies, I am completely new to Django and Python.
I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:
```
list = List.objects.all()[0]
```
Is there a way to get the length ... | I haven't tried this yet, but I'd look at the *latest()* operator on [QuerySets](http://docs.djangoproject.com/en/dev/ref/models/querysets/#ref-models-querysets):
> latest(field\_name=None)
>
> Returns the latest object in the
> table, by date, using the field\_name
> provided as the date field.
>
> This example retur... |
Django - Getting last object created, simultaneous filters | 1,256,190 | 21 | 2009-08-10T17:35:15Z | 1,256,899 | 11 | 2009-08-10T19:58:19Z | [
"python",
"django",
"filter",
"django-views"
] | Apologies, I am completely new to Django and Python.
I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:
```
list = List.objects.all()[0]
```
Is there a way to get the length ... | For the largest primary key, try this:
```
List.objects.order_by('-pk')[0]
```
Note that using `pk` works regardless of the actual name of the field defined as your primary key. |
Django - Getting last object created, simultaneous filters | 1,256,190 | 21 | 2009-08-10T17:35:15Z | 1,886,857 | 13 | 2009-12-11T09:28:20Z | [
"python",
"django",
"filter",
"django-views"
] | Apologies, I am completely new to Django and Python.
I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:
```
list = List.objects.all()[0]
```
Is there a way to get the length ... | this works!
`Model.objects.latest('field')` - field can be id. that will be the latest id |
Need help in refactoring my python script | 1,256,704 | 3 | 2009-08-10T19:18:13Z | 1,256,723 | 12 | 2009-08-10T19:24:29Z | [
"python"
] | I have a python script which process a file line by line, if the line
matches a regex, it calls a function to handle it.
My question is is there a better write to refactor my script. The
script works, but as it is, i need to keep indent to the right of the
editor as I add more and more regex for my file.
Thank you fo... | I'd switch to using a data structure mapping regexes to functions. Something like:
```
map = { reg1: handleReg1, reg2: handleReg2, etc }
```
Then you just loop through them:
```
for reg, handler in map.items():
result = reg.match(line)
if result:
handler(result)
break
```
If you need the match... |
Iterate over pairs in a list (circular fashion) in Python | 1,257,413 | 31 | 2009-08-10T21:50:38Z | 1,257,446 | 26 | 2009-08-10T21:57:01Z | [
"list",
"iteration",
"tuples",
"python"
] | The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).
I've thought about two unpythonic ways of doing it:
```
def pairs(lst):
n = len(lst)
for i in range(n):
yield lst[i],lst[(i+1)%n]
```
and:
```
def pairs(lst):
re... | ```
def pairs(lst):
i = iter(lst)
first = prev = item = i.next()
for item in i:
yield prev, item
prev = item
yield item, first
```
Works on any non-empty sequence, no indexing required. |
Iterate over pairs in a list (circular fashion) in Python | 1,257,413 | 31 | 2009-08-10T21:50:38Z | 1,257,624 | 7 | 2009-08-10T22:37:22Z | [
"list",
"iteration",
"tuples",
"python"
] | The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).
I've thought about two unpythonic ways of doing it:
```
def pairs(lst):
n = len(lst)
for i in range(n):
yield lst[i],lst[(i+1)%n]
```
and:
```
def pairs(lst):
re... | I've coded myself the tuple general versions, I like the first one for it's ellegant simplicity, the more I look at it, the more Pythonic it feels to me... after all, what is more Pythonic than a one liner with zip, asterisk argument expansion, list comprehensions, list slicing, list concatenation and "range"?
```
def... |
python: slow timeit() function | 1,257,727 | 12 | 2009-08-10T23:09:51Z | 1,257,737 | 23 | 2009-08-10T23:12:42Z | [
"python",
"timer",
"timeit"
] | When I run the code below outside of timeit(), it appears to complete instantaneously. However when I run it within the timeit() function, it takes much longer. Why?
```
>>> import timeit
>>> t = timeit.Timer("3**4**5")
>>> t.timeit()
16.55522028637718
```
Using:
Python 3.1 (x86) -
AMD Athlon 64 X2 -
WinXP (32 bit) | The `timeit()` function runs the code many times (default one million) and takes an average of the timings.
To run the code only once, do this:
```
t.timeit(1)
```
but that will give you skewed results - it repeats for good reason.
To get the per-loop time having let it repeat, divide the result by the number of lo... |
python datetime strptime wildcard | 1,258,199 | 13 | 2009-08-11T02:23:47Z | 1,258,247 | 18 | 2009-08-11T02:41:28Z | [
"python",
"datetime",
"parsing",
"strptime"
] | I want to parse dates like these into a datetime object:
* December 12th, 2008
* January 1st, 2009
The following will work for the first date:
```
datetime.strptime("December 12th, 2008", "%B %dth, %Y")
```
but will fail for the second because of the suffix to the day number ('st'). So, is there an undocumented wil... | Try using the dateutil.parser module.
```
import dateutil.parser
date1 = dateutil.parser.parse("December 12th, 2008")
date2 = dateutil.parser.parse("January 1st, 2009")
```
Additional documentation can be found here: <http://labix.org/python-dateutil> |
python datetime strptime wildcard | 1,258,199 | 13 | 2009-08-11T02:23:47Z | 1,258,248 | 7 | 2009-08-11T02:42:09Z | [
"python",
"datetime",
"parsing",
"strptime"
] | I want to parse dates like these into a datetime object:
* December 12th, 2008
* January 1st, 2009
The following will work for the first date:
```
datetime.strptime("December 12th, 2008", "%B %dth, %Y")
```
but will fail for the second because of the suffix to the day number ('st'). So, is there an undocumented wil... | strptime is tricky because it relies on the underlying C library for its implementation, so some details differ between platforms. There doesn't seem to be a way to match the characters you need to. But you could clean the data first:
```
# Remove ordinal suffixes from numbers.
date_in = re.sub(r"(st|nd|rd|th),", ",",... |
python datetime strptime wildcard | 1,258,199 | 13 | 2009-08-11T02:23:47Z | 1,258,249 | 8 | 2009-08-11T02:42:26Z | [
"python",
"datetime",
"parsing",
"strptime"
] | I want to parse dates like these into a datetime object:
* December 12th, 2008
* January 1st, 2009
The following will work for the first date:
```
datetime.strptime("December 12th, 2008", "%B %dth, %Y")
```
but will fail for the second because of the suffix to the day number ('st'). So, is there an undocumented wil... | You need Gustavo Niemeyer's [python\_dateutil](http://labix.org/python-dateutil) -- once it's installed,
```
>>> from dateutil import parser
>>> parser.parse('December 12th, 2008')
datetime.datetime(2008, 12, 12, 0, 0)
>>> parser.parse('January 1st, 2009')
datetime.datetime(2009, 1, 1, 0, 0)
>>>
``` |
How to get user input during a while loop without blocking | 1,258,566 | 2 | 2009-08-11T05:27:05Z | 1,258,581 | 9 | 2009-08-11T05:33:24Z | [
"python"
] | I'm trying to write a while loop that constantly updates the screen by using os.system("clear") and then printing out a different text message every few seconds. How do I get user input during the loop? raw\_input() just pauses and waits, which is not the functionality I want.
```
import os
import time
string = "the ... | The [select](http://docs.python.org/library/select.html) module in Python's standard library may be what you're looking for -- standard input has FD 0, though you may also need to put a terminal in "raw" (as opposed to "cooked") mode, on unix-y systems, to get single keypresses from it as opposed to whole lines complet... |
fuzzy timestamp parsing with Python | 1,258,712 | 5 | 2009-08-11T06:29:11Z | 1,258,858 | 8 | 2009-08-11T07:21:47Z | [
"python",
"date",
"parsing",
"timestamp"
] | Is there a Python module to interpret fuzzy timestamps like the date command in unix:
```
> date -d "2 minutes ago"
Tue Aug 11 16:24:05 EST 2009
```
The closest I have found so far is dateutil.parser, which fails for the above example.
thanks | Check out this open source module: [parsedatetime](https://github.com/bear/parsedatetime) |
Python Subprocess - Redirect stdout/err to two places | 1,258,863 | 9 | 2009-08-11T07:22:29Z | 1,258,929 | 8 | 2009-08-11T07:44:36Z | [
"python",
"redirect",
"subprocess",
"stdout"
] | I have a small python script which invokes an external process using `subprocess`. I want to redirect stdout and stderr to both a log file and to the terminal.
How can this be done? | You can do this with [`subprocess.PIPE`](http://docs.python.org/library/subprocess.html#subprocess.PIPE).
You can find [some sample code here](http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html). |
Python: How can I choose which module to import when they are named the same | 1,259,106 | 6 | 2009-08-11T08:44:44Z | 1,259,275 | 9 | 2009-08-11T09:22:51Z | [
"python",
"import",
"namespaces"
] | Lets say I'm in a file called `openid.py` and I do :
```
from openid.consumer.discover import discover, DiscoveryFailure
```
I have the `openid` module on my pythonpath but the interpreter seems to be trying to use my `openid.py` file. How can I get the library version?
(Of course, something other than the obvious '... | Thats the reason absolute imports have been chosen as the new default behaviour. However, they are not yet the default in 2.6 (maybe in 2.7...). You can get their behaviour now by importing them from the future:
```
from __future__ import absolute_import
```
You can find out more about this in the PEP metnioned by Ni... |
django Datefield to Unix timestamp | 1,259,219 | 26 | 2009-08-11T09:11:07Z | 1,259,378 | 23 | 2009-08-11T09:45:05Z | [
"python",
"django",
"unix-timestamp"
] | Hello
In a model I have a such field:
mydate = models.DateField()
now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input.
Thanks | **edit: please check the second answer, it has a much better solution**
In python code, you can do this to convert a date or datetime to the Unix Epoch
```
import time
epoch = int(time.mktime(mydate.timetuple())*1000)
```
This doesn't work in a Django template though, so you need a custom filter, e.g:
```
import ti... |
django Datefield to Unix timestamp | 1,259,219 | 26 | 2009-08-11T09:11:07Z | 3,376,435 | 82 | 2010-07-31T01:44:11Z | [
"python",
"django",
"unix-timestamp"
] | Hello
In a model I have a such field:
mydate = models.DateField()
now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input.
Thanks | I know another answer was accepted a while ago, but this question appears high on Google's search results, so I will add another answer.
If you are working at the template level, you can use the [`U` parameter](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#std%3atemplatefilter-date) to the... |
django Datefield to Unix timestamp | 1,259,219 | 26 | 2009-08-11T09:11:07Z | 7,387,012 | 47 | 2011-09-12T11:17:02Z | [
"python",
"django",
"unix-timestamp"
] | Hello
In a model I have a such field:
mydate = models.DateField()
now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input.
Thanks | And if you're not in the template layer, you can still use the same underlying django utils. Ex:
```
from django.utils.dateformat import format
print format(mymodel.mydatefield, 'U')
``` |
Is it a good idea to use super() in Python? | 1,259,547 | 10 | 2009-08-11T10:32:51Z | 1,259,665 | 8 | 2009-08-11T10:59:23Z | [
"python",
"oop",
"super"
] | Or should I just explicitly reference the superclasses whose methods I want to call?
It seems brittle to repeat the names of super classes when referencing their constructors, but this page <http://fuhm.net/super-harmful/> makes some good arguments against using super(). | The book [Expert Python Programming](http://www.packtpub.com/expert-python-programming/) has discussed the topic of "super pitfalls" in chapter 3. It is worth reading. Below is the book's conclusion:
> Super usage has to be consistent: In a class hierarchy, super should be used everywhere or nowhere. Mixing super and ... |
How can I use Emacs Flymake mode for python with pyflakes and pylint checking code? | 1,259,873 | 22 | 2009-08-11T11:47:53Z | 1,393,590 | 34 | 2009-09-08T11:57:18Z | [
"python",
"emacs",
"pylint",
"pep8",
"pyflakes"
] | For checking code in python mode I use flymake with [pyflakes](http://www.emacswiki.org/cgi-bin/wiki/PythonMode#toc8)
Also I want check code style (pep8) with pylint (description on the same page with pyflakes)
This solutions work.
But I can't configure flymake for work with pyflakes and pylint together.
How can I do... | Well, flymake is just looking for a executable command thats output lines in a predefined format. You can make a shell script for example that will call successively all the checkers you want...
You must also make sure that your script ends by returning errorlevel 0. So this is an example:
This is what I've done in a... |
How can I use Emacs Flymake mode for python with pyflakes and pylint checking code? | 1,259,873 | 22 | 2009-08-11T11:47:53Z | 1,621,489 | 7 | 2009-10-25T17:31:25Z | [
"python",
"emacs",
"pylint",
"pep8",
"pyflakes"
] | For checking code in python mode I use flymake with [pyflakes](http://www.emacswiki.org/cgi-bin/wiki/PythonMode#toc8)
Also I want check code style (pep8) with pylint (description on the same page with pyflakes)
This solutions work.
But I can't configure flymake for work with pyflakes and pylint together.
How can I do... | Usually one can enable flymake mode in the python-mode-hook. Unfortunately that causes issues with things like py-execute-buffer which create temporary buffers which invoke the hook and then cause flymake mode to hiccup because of the lack of "real file". The solution is to modify the conditions where you add the hook:... |
Python : Assert that variable is instance method? | 1,259,963 | 25 | 2009-08-11T12:10:54Z | 1,260,881 | 8 | 2009-08-11T14:53:48Z | [
"python",
"methods",
"instance",
"assert"
] | How can one check if a variable is an instance method or not? I'm using python 2.5.
Something like this:
```
class Test:
def method(self):
pass
assert is_instance_method(Test().method)
``` | If you want to know if it is precisely an instance method use the following function. (It considers methods that are defined on a metaclass and accessed on a class class methods, although they could also be considered instance methods)
```
import types
def is_instance_method(obj):
"""Checks if an object is a bound... |
Python : Assert that variable is instance method? | 1,259,963 | 25 | 2009-08-11T12:10:54Z | 1,260,997 | 39 | 2009-08-11T15:10:56Z | [
"python",
"methods",
"instance",
"assert"
] | How can one check if a variable is an instance method or not? I'm using python 2.5.
Something like this:
```
class Test:
def method(self):
pass
assert is_instance_method(Test().method)
``` | [`inspect.ismethod`](http://docs.python.org/library/inspect.html#inspect.ismethod) is what you want to find out if you definitely have a method, rather than just something you can call.
```
import inspect
def foo(): pass
class Test(object):
def method(self): pass
print inspect.ismethod(foo) # False
print inspec... |
OS locale support for use in Python | 1,259,971 | 15 | 2009-08-11T12:12:19Z | 1,260,005 | 21 | 2009-08-11T12:20:27Z | [
"python",
"locale"
] | The following Python code works on my Windows machine (Python 2.5.4), but doesn't on my Debian machine (Python 2.5.0). I'm guessing it's OS dependent.
```
import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
```
I receive the following error:
```
Traceback (most recent call last):
File "<s... | It is OS dependent.
To get the list of local available you can use `locale -a` in a shell
I think the local you want is something like [`Windows-1252`](http://en.wikipedia.org/wiki/Windows-1252) |
OS locale support for use in Python | 1,259,971 | 15 | 2009-08-11T12:12:19Z | 1,260,101 | 7 | 2009-08-11T12:40:55Z | [
"python",
"locale"
] | The following Python code works on my Windows machine (Python 2.5.4), but doesn't on my Debian machine (Python 2.5.0). I'm guessing it's OS dependent.
```
import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
```
I receive the following error:
```
Traceback (most recent call last):
File "<s... | Look inside the `locale.locale_alias` dictionary.
```
>>> import locale
>>> len(locale.locale_alias)
789
>>> locale.locale_alias.keys()[:5]
['ko_kr.euc', 'is_is', 'ja_jp.mscode', 'kw_gb@euro', 'yi_us.cp1255']
>>>
```
(In my 2.6.2 installation there are 789 locale names.) |
OS locale support for use in Python | 1,259,971 | 15 | 2009-08-11T12:12:19Z | 5,661,043 | 9 | 2011-04-14T09:24:28Z | [
"python",
"locale"
] | The following Python code works on my Windows machine (Python 2.5.4), but doesn't on my Debian machine (Python 2.5.0). I'm guessing it's OS dependent.
```
import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
```
I receive the following error:
```
Traceback (most recent call last):
File "<s... | try
```
apt-get install locales-all
```
for me it works like a charm |
Locking a custom dictionary | 1,260,649 | 2 | 2009-08-11T14:16:08Z | 1,260,683 | 12 | 2009-08-11T14:21:13Z | [
"python",
"dictionary",
"locking"
] | Good day pythonians,
I want to make a custom dictionary with two main features:
1. All keys are declared on creation
2. It is impossible to add new keys or modify current ones (values are still modifiable)
Right now code is this:
```
class pick(dict):
"""This will make delicious toffee when finished"""
def __... | Override the `__setitem__` method with your desired behavior, call `dict.__setitem__(self, key, value`) to modify the base dictionary without going through your base logic.
```
class ImmutableDict(dict):
def __setitem__(self, key, value):
if key not in self:
raise KeyError("Immutable dict")
... |
Python: import a file from a subdirectory | 1,260,792 | 180 | 2009-08-11T14:39:05Z | 1,260,813 | 232 | 2009-08-11T14:42:10Z | [
"python",
"module",
"subdirectory",
"python-import"
] | I have a file called `tester.py`, located on `/project`.
`/project` has a subdirectory called `lib`, with a file called `BoxTime.py`:
```
/project/tester.py
/project/lib/BoxTime.py
```
I want to import `BoxTime` from `tester`. I have tried this:
```
import lib.BoxTime
```
Which resulted:
```
Traceback (most recen... | Take a look at the Packages documentation (Section 6.4) here: <http://docs.python.org/tutorial/modules.html>
In short, you need to put a blank file named
```
__init__.py
```
in the "lib" directory. |
Python: import a file from a subdirectory | 1,260,792 | 180 | 2009-08-11T14:39:05Z | 1,260,814 | 8 | 2009-08-11T14:42:13Z | [
"python",
"module",
"subdirectory",
"python-import"
] | I have a file called `tester.py`, located on `/project`.
`/project` has a subdirectory called `lib`, with a file called `BoxTime.py`:
```
/project/tester.py
/project/lib/BoxTime.py
```
I want to import `BoxTime` from `tester`. I have tried this:
```
import lib.BoxTime
```
Which resulted:
```
Traceback (most recen... | Try `import .lib.BoxTime`. For more information read about relative import in [PEP 328](http://dinsdale.python.org/dev/peps/pep-0328/#guido-s-decision). |
Python: import a file from a subdirectory | 1,260,792 | 180 | 2009-08-11T14:39:05Z | 1,260,832 | 15 | 2009-08-11T14:44:44Z | [
"python",
"module",
"subdirectory",
"python-import"
] | I have a file called `tester.py`, located on `/project`.
`/project` has a subdirectory called `lib`, with a file called `BoxTime.py`:
```
/project/tester.py
/project/lib/BoxTime.py
```
I want to import `BoxTime` from `tester`. I have tried this:
```
import lib.BoxTime
```
Which resulted:
```
Traceback (most recen... | Does your lib directory contain a `__init__.py` file?
Python uses `__init__.py` to determine if a directory is a module. |
Python: import a file from a subdirectory | 1,260,792 | 180 | 2009-08-11T14:39:05Z | 1,260,846 | 63 | 2009-08-11T14:46:34Z | [
"python",
"module",
"subdirectory",
"python-import"
] | I have a file called `tester.py`, located on `/project`.
`/project` has a subdirectory called `lib`, with a file called `BoxTime.py`:
```
/project/tester.py
/project/lib/BoxTime.py
```
I want to import `BoxTime` from `tester`. I have tried this:
```
import lib.BoxTime
```
Which resulted:
```
Traceback (most recen... | * Create a subdirectory named lib.
* Create an empty file named lib\\_\_init\_\_.py.
* In lib\BoxTime.py, write a function foo() like this:
```
def foo():
print "foo!"
```
* In your client code in the directory above lib, write:
```
from lib import BoxTime
BoxTime.foo()
```
* Run your client code.... |
Python: import a file from a subdirectory | 1,260,792 | 180 | 2009-08-11T14:39:05Z | 14,999,050 | 19 | 2013-02-21T09:47:42Z | [
"python",
"module",
"subdirectory",
"python-import"
] | I have a file called `tester.py`, located on `/project`.
`/project` has a subdirectory called `lib`, with a file called `BoxTime.py`:
```
/project/tester.py
/project/lib/BoxTime.py
```
I want to import `BoxTime` from `tester`. I have tried this:
```
import lib.BoxTime
```
Which resulted:
```
Traceback (most recen... | You can try inserting it in `sys.path`:
```
sys.path.insert(0, './lib')
import BoxTime
``` |
Pythonic way of searching for a substring in a list | 1,260,947 | 3 | 2009-08-11T15:03:59Z | 1,261,016 | 15 | 2009-08-11T15:15:33Z | [
"string",
"list",
"python",
"substrings"
] | I have a list of strings - something like
```
mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text']
```
I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar\*. My current solut... | You can also use a list comprehension :
```
matches = [s for s in mytext if 'foobar' in s]
```
(and if you were really looking for strings *starting* with 'foobar' as THC4k noticed, consider the following :
```
matches = [s for s in mytext if s.startswith('foobar')]
``` |
Pythonic way of searching for a substring in a list | 1,260,947 | 3 | 2009-08-11T15:03:59Z | 1,261,192 | 9 | 2009-08-11T15:39:34Z | [
"string",
"list",
"python",
"substrings"
] | I have a list of strings - something like
```
mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text']
```
I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar\*. My current solut... | If you really want the FIRST occurrence of a string that STARTS WITH foobar (which is what your words say, though very different from your code, all answers provided, your mention of grep -- how contradictory can you get?-), try:
```
found = next((s for s in mylist if s.startswith('foobar')), '')
```
this gives an em... |
cannot override sys.excepthook | 1,261,668 | 4 | 2009-08-11T16:58:23Z | 1,262,091 | 7 | 2009-08-11T18:18:53Z | [
"python",
"debugging",
"ipython",
"pdb"
] | I try to customize behavior of `sys.excepthook` as described by [the recipe](http://mail.python.org/pipermail/python-list/2001-April/079168.html).
in ipython:
```
:import pdb, sys, traceback
:def info(type, value, tb):
: traceback.print_exception(type, value, tb)
: pdb.pm()
:sys.excepthook = info
:--
>>> x[10] ... | ipython, which you're using instead of the normal Python interactive shell, traps all exceptions itself and does NOT use sys.excepthook. Run it as `ipython -pdb` instead of just `ipython`, and it will automatically invoke pdb upon uncaught exceptions, just as you are trying to do with your excepthook. |
Python nonlocal statement | 1,261,875 | 99 | 2009-08-11T17:36:24Z | 1,261,892 | 46 | 2009-08-11T17:40:52Z | [
"python",
"closures",
"global",
"python-nonlocal"
] | What does the Python `nonlocal` statement do (in Python 3.0 and later)?
There's no documentation on the official Python website and `help("nonlocal")` does not work, either. | In short, it lets you assign values to a variable in an outer (but non-global) scope. See [PEP 3104](http://www.python.org/dev/peps/pep-3104/) for all the gory details. |
Python nonlocal statement | 1,261,875 | 99 | 2009-08-11T17:36:24Z | 1,261,952 | 21 | 2009-08-11T17:50:45Z | [
"python",
"closures",
"global",
"python-nonlocal"
] | What does the Python `nonlocal` statement do (in Python 3.0 and later)?
There's no documentation on the official Python website and `help("nonlocal")` does not work, either. | A google search for "python nonlocal" turned up the Proposal, [PEP 3104](http://www.python.org/dev/peps/pep-3104/), which fully describes the syntax and reasoning behind the statement. in short, it works in exactly the same way as the `global` statement, except that it is used to refer to variables that are neither glo... |
Python nonlocal statement | 1,261,875 | 99 | 2009-08-11T17:36:24Z | 1,261,961 | 151 | 2009-08-11T17:53:30Z | [
"python",
"closures",
"global",
"python-nonlocal"
] | What does the Python `nonlocal` statement do (in Python 3.0 and later)?
There's no documentation on the official Python website and `help("nonlocal")` does not work, either. | Compare this, without using `nonlocal`:
```
x = 0
def outer():
x = 1
def inner():
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 2
# outer: 1
# global: 0
```
To this, using **`nonlocal`**, where `inner()`'s `x` is now also `outer()`'s `x`:
... |
Python decorators in classes | 1,263,451 | 65 | 2009-08-11T23:01:45Z | 1,263,545 | 51 | 2009-08-11T23:33:46Z | [
"python",
"class",
"decorator",
"self"
] | Can one write sth like:
```
class Test(object):
def _decorator(self, foo):
foo()
@self._decorator
def bar(self):
pass
```
This fails: self in @self is unknown
I also tried:
```
@Test._decorator(self)
```
which also fails: Test unknown
If would like to temp. change some instance variab... | What you're wanting to do isn't possible. Take, for instance, whether or not the code below looks valid:
```
class Test(object):
def _decorator(self, foo):
foo()
def bar(self):
pass
bar = self._decorator(bar)
```
It, of course, isn't valid since `self` isn't defined at that point. The sa... |
Python decorators in classes | 1,263,451 | 65 | 2009-08-11T23:01:45Z | 1,263,782 | 119 | 2009-08-12T01:13:16Z | [
"python",
"class",
"decorator",
"self"
] | Can one write sth like:
```
class Test(object):
def _decorator(self, foo):
foo()
@self._decorator
def bar(self):
pass
```
This fails: self in @self is unknown
I also tried:
```
@Test._decorator(self)
```
which also fails: Test unknown
If would like to temp. change some instance variab... | Would something like this do what you need?
```
class Test(object):
def _decorator(foo):
def magic( self ) :
print "start magic"
foo( self )
print "end magic"
return magic
@_decorator
def bar( self ) :
print "normal call"
test = Test()
test.bar... |
Another absolute import problem | 1,263,474 | 5 | 2009-08-11T23:10:06Z | 8,295,885 | 8 | 2011-11-28T12:34:56Z | [
"python"
] | I'm having problems with my own modules overriding built in Python ones (specifically the logging module). Here's my project layout:
```
run.py
package/
__init__.py
logging/
__init__.py
...
```
run.py
```
from package import main
main()
```
package/\_\_init\_\_.py
```
from ... | Relative and absolute imports (PEP 328) are not the problem here.
What happens is that when a module in a package is imported, it is implicitly added to this package's namespace. So
```
from package.logging import Logging
```
not only adds 'Logging' to package.*\_dict*\_, but also adds 'logging' (the newly import lo... |
How do I convert unicode characters to floats in Python? | 1,263,796 | 10 | 2009-08-12T01:23:15Z | 1,263,811 | 21 | 2009-08-12T01:28:06Z | [
"python",
"unicode",
"floating-point"
] | I am parsing a webpage which has Unicode representations of fractions. I would like to be able to take those strings directly and convert them to floats. For example:
"â
" would become 0.2
Any suggestions of how to do this in Python? | You want to use the [unicodedata](http://docs.python.org/library/unicodedata.html) module:
```
import unicodedata
unicodedata.numeric(u'â
')
```
This will print:
```
0.20000000000000001
```
If the character does not have a numeric value, then `unicodedata.numeric(unichr[, default])` will return default, or if defa... |
Mechanize and BeautifulSoup for PHP? | 1,263,800 | 18 | 2009-08-12T01:24:42Z | 1,263,812 | 8 | 2009-08-12T01:28:32Z | [
"php",
"python",
"beautifulsoup",
"mechanize"
] | I was wondering if there was anything similar like Mechanize or BeautifulSoup for PHP? | SimpleTest provides you with similar functionality:
<http://www.simpletest.org/en/browser_documentation.html> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.