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
Distributing Python programs
1,950,218
8
2009-12-23T01:28:56Z
1,950,233
7
2009-12-23T01:35:07Z
[ "python" ]
How do I let my friends use my Python programs? They don't have python installed, but they can use command line programs. I don't have the skill to write GUI. Let, say I am writing some calculus calculator, with a lot of custom modules and files. How do I share it?
another alternative you can try is [Portable python](http://www.portablepython.com/wiki/PortablePython1.1Py2.6.1).
pyyaml: dumping without tags
1,950,306
40
2009-12-23T02:03:11Z
1,950,399
50
2009-12-23T02:34:41Z
[ "python", "yaml", "pyyaml" ]
I have ``` >>> import yaml >>> yaml.dump(u'abc') "!!python/unicode 'abc'\n" ``` But I want ``` >>> import yaml >>> yaml.dump(u'abc', magic='something') 'abc\n' ``` What magic param forces no tagging?
You can use `safe_dump` instead of `dump`. Just keep in mind that it won't be able to represent arbitrary Python objects then. Also, when you `load` the YAML, you will get a `str` object instead of `unicode`.
pyyaml: dumping without tags
1,950,306
40
2009-12-23T02:03:11Z
1,951,616
11
2009-12-23T09:25:38Z
[ "python", "yaml", "pyyaml" ]
I have ``` >>> import yaml >>> yaml.dump(u'abc') "!!python/unicode 'abc'\n" ``` But I want ``` >>> import yaml >>> yaml.dump(u'abc', magic='something') 'abc\n' ``` What magic param forces no tagging?
How about this: ``` def unicode_representer(dumper, uni): node = yaml.ScalarNode(tag=u'tag:yaml.org,2002:str', value=uni) return node yaml.add_representer(unicode, unicode_representer) ``` This seems to make dumping unicode objects work the same as dumping str objects for me (Python 2.6). ``` In [72]: yaml....
Is it Pythonic to check function argument types?
1,950,386
16
2009-12-23T02:31:03Z
1,950,420
23
2009-12-23T02:42:01Z
[ "python", "typechecking" ]
I know, type checking function arguments is generally frowned upon in Python, but I think I've come up with a situation where it makes sense to do so. In my project I have an Abstract Base Class `Coord`, with a subclass `Vector`, which has more features like rotation, changing magnitude, etc. Lists and tuples of numbe...
Your taste may vary, but the Pythonic(tm) style is to just go ahead and use objects as you need to. If they don't support the operations you're attempting, an exception will be raised. This is known as [duck typing](http://en.wikipedia.org/wiki/Duck%5Ftyping). There are a few reasons for favoring this style: first, it...
Is it Pythonic to check function argument types?
1,950,386
16
2009-12-23T02:31:03Z
1,950,564
9
2009-12-23T03:38:10Z
[ "python", "typechecking" ]
I know, type checking function arguments is generally frowned upon in Python, but I think I've come up with a situation where it makes sense to do so. In my project I have an Abstract Base Class `Coord`, with a subclass `Vector`, which has more features like rotation, changing magnitude, etc. Lists and tuples of numbe...
One of the reasons Duck Typing is encouraged in Python is that someone might wrap one of your objects, and then it will look like the wrong type, but still work. Here is an example of a class that wraps an object. A `LoggedObject` acts in all ways like the object it wraps, but when you call the `LoggedObject`, it logs...
What does classmethod do in this code?
1,950,414
13
2009-12-23T02:39:39Z
1,950,927
52
2009-12-23T05:59:07Z
[ "python" ]
In django.utils.tree.py: ``` def _new_instance(cls, children=None, connector=None, negated=False): obj = Node(children, connector, negated) obj.__class__ = cls return obj _new_instance = classmethod(_new_instance) ``` I don't know what `classmethod` does in this code sample. Can someone ex...
`classmethod` is a descriptor, wrapping a function, and you can call the resulting object on a class or (equivalently) an instance thereof: ``` >>> class x(object): ... def c1(*args): print 'c1', args ... c1 = classmethod(c1) ... @classmethod ... def c2(*args): print 'c2', args ... >>> inst = x() >>> x.c1() c...
wxPython file dialog error: missing "|" in the wildcard string!
1,950,454
2
2009-12-23T02:56:55Z
1,950,466
7
2009-12-23T03:01:45Z
[ "python", "wxpython" ]
I am on Windows7, using Python 2.6 and wxPython 2.8.10.1. I am trying to get this Open File dialog to work but am running into a weird error. This looks like a valid wildcard string to me, but whenever I choose a file and click 'Ok' on the File Dialog, I get this: ``` Traceback (most recent call last): File "D:\Projec...
The wildcard string has a quirky format, borrowed from Win32: ``` Desc1|wildcard1|Desc2|wildcard2 ... ``` There should be an odd number of pipes, so that the pipe-separated pieces form pairs, a description, and a wildcard. For example: ``` Spreadsheet (*.xls)|*.xls|Plain-old text (*.txt)|*.txt|Random noise|*.dat ```...
Library for programming Abstract Syntax Trees in Python
1,950,578
10
2009-12-23T03:40:22Z
1,950,592
7
2009-12-23T03:44:58Z
[ "python", "abstract-syntax-tree" ]
I'm creating a tree to represent a simple language. I'm very familiar with Abstract Syntax Trees, and have worked on frameworks for building and using them in C++. Is there a standard python library for specifying or manipulating arbitrary ASTs? Failing that, is there a tree library which is useful for the same purpose...
ASTs are very simple to implement in Python. For example, for my [pycparser](https://github.com/eliben/pycparser) project (a complete C parser in Python) I've implemented ASTs based on ideas borrowed from Python's modules. The various AST nodes are specified in a YAML configuration file, and I generate Python code for ...
Python - Things I shouldn't be doing?
1,951,012
4
2009-12-23T06:31:03Z
1,951,172
21
2009-12-23T07:17:34Z
[ "python" ]
I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code: ``` ... junk_block = "".join(open("foo.txt","rb").read().split()) ... ``` I don't do this anymore because I can see that it makes code harder to read, but would the code run slower if I split the sta...
As long as you're inside a function (**not** at module top level), assigning intermediate results to local barenames has an essentially-negligible cost (at module top level, assigning to the "local" barenames implies churning on a dict -- the module's `__dict__` -- and is measurably costlier than it would be within a f...
Parsing a C header file in Python
1,951,421
13
2009-12-23T08:36:07Z
1,951,444
8
2009-12-23T08:42:05Z
[ "python", "c" ]
Does anyone know a spiffy way to use C header files in Python? For example I have a C program that includes a global variable: ``` typedef struct ImageInfo { uint8_t revisionMajor; uint8_t revisionMinor; uint16_t checksum; } ImageInfo; ImageInfo gImageInfo; /* Placed at a specific address by the li...
Take a look at [pygccxml](http://www.language-binding.net/pygccxml/pygccxml.html). I use it to build in-memory graphs of my C / C++ source code that I can use as the basis for many code generation tasks. PS: When I first started out with Python based code-generation I actually tried to write a parser myself: save your...
Parsing a C header file in Python
1,951,421
13
2009-12-23T08:36:07Z
1,951,468
11
2009-12-23T08:47:35Z
[ "python", "c" ]
Does anyone know a spiffy way to use C header files in Python? For example I have a C program that includes a global variable: ``` typedef struct ImageInfo { uint8_t revisionMajor; uint8_t revisionMinor; uint16_t checksum; } ImageInfo; ImageInfo gImageInfo; /* Placed at a specific address by the li...
[Have a look at this C++ header parser written in Python](http://sourceforge.net/projects/cppheaderparser/). You can also write your own parser using any of these tools: * [pyparsing](http://pyparsing.wikispaces.com/) * [ply](http://www.dabeaz.com/ply/) * [lepl](http://www.acooke.org/lepl/) [and a lot more](http://...
Parsing a C header file in Python
1,951,421
13
2009-12-23T08:36:07Z
1,953,543
22
2009-12-23T15:47:52Z
[ "python", "c" ]
Does anyone know a spiffy way to use C header files in Python? For example I have a C program that includes a global variable: ``` typedef struct ImageInfo { uint8_t revisionMajor; uint8_t revisionMinor; uint16_t checksum; } ImageInfo; ImageInfo gImageInfo; /* Placed at a specific address by the li...
This was mentioned on SO yesterday; I haven't had a chance to check it out more thoroughly yet, but I'm meaning to. The `pycparser`, a "C parser and AST generator written in Python". <https://github.com/eliben/pycparser>
In Python, how do I determine if an object is iterable?
1,952,464
566
2009-12-23T12:13:55Z
1,952,481
449
2009-12-23T12:16:43Z
[ "python", "iterable" ]
Is there a method like `isiterable`? The only solution I have found so far is to call ``` hasattr(myObj, '__iter__') ``` But I am not sure how fool-proof this is.
1. Checking for `__iter__` works on sequence types, but it would fail on e.g. strings. I would like to know the right answer too, until then, here is one possibility (which would work on strings, too): ``` try: some_object_iterator = iter(some_object) except TypeError, te: print some_object, 'is...
In Python, how do I determine if an object is iterable?
1,952,464
566
2009-12-23T12:13:55Z
1,952,485
22
2009-12-23T12:17:39Z
[ "python", "iterable" ]
Is there a method like `isiterable`? The only solution I have found so far is to call ``` hasattr(myObj, '__iter__') ``` But I am not sure how fool-proof this is.
This isn't sufficient: the object returned by `__iter__` must implement the iteration protocol (i.e. `next` method). See the relevant section in the [documentation](http://docs.python.org/library/stdtypes.html#iterator-types). In Python, a good practice is to " try and see " instead of "checking".
In Python, how do I determine if an object is iterable?
1,952,464
566
2009-12-23T12:13:55Z
1,952,507
9
2009-12-23T12:21:12Z
[ "python", "iterable" ]
Is there a method like `isiterable`? The only solution I have found so far is to call ``` hasattr(myObj, '__iter__') ``` But I am not sure how fool-proof this is.
You could try this: ``` def iterable(a): try: (x for x in a) return True except TypeError: return False ``` If we can make a generator that iterates over it (but never use the generator so it doesn't take up space), it's iterable. Seems like a "duh" kind of thing. Why do you need to de...
In Python, how do I determine if an object is iterable?
1,952,464
566
2009-12-23T12:13:55Z
1,952,508
13
2009-12-23T12:21:35Z
[ "python", "iterable" ]
Is there a method like `isiterable`? The only solution I have found so far is to call ``` hasattr(myObj, '__iter__') ``` But I am not sure how fool-proof this is.
``` try: #treat object as iterable except TypeError, e: #object is not actually iterable ``` Don't run checks to see ~~if your duck really is a duck~~ to see if it is iterable or not, treat it as if it was and complain if it wasn't.
In Python, how do I determine if an object is iterable?
1,952,464
566
2009-12-23T12:13:55Z
1,952,655
428
2009-12-23T12:53:38Z
[ "python", "iterable" ]
Is there a method like `isiterable`? The only solution I have found so far is to call ``` hasattr(myObj, '__iter__') ``` But I am not sure how fool-proof this is.
## Duck typing ``` try: iterator = iter(theElement) except TypeError: # not iterable else: # iterable # for obj in iterator: # pass ``` ## Type checking Use the [Abstract Base Classes](http://docs.python.org/library/abc.html). They need at least Python 2.6 and work only for new-style classes. ``` i...
In Python, how do I determine if an object is iterable?
1,952,464
566
2009-12-23T12:13:55Z
1,952,735
9
2009-12-23T13:13:41Z
[ "python", "iterable" ]
Is there a method like `isiterable`? The only solution I have found so far is to call ``` hasattr(myObj, '__iter__') ``` But I am not sure how fool-proof this is.
I found a nice solution [here](http://bytes.com/topic/python/answers/514838-how-test-if-object-sequence-iterable): ``` isiterable = lambda obj: isinstance(obj, basestring) \ or getattr(obj, '__iter__', False) ```
In Python, how do I determine if an object is iterable?
1,952,464
566
2009-12-23T12:13:55Z
1,952,851
9
2009-12-23T13:35:47Z
[ "python", "iterable" ]
Is there a method like `isiterable`? The only solution I have found so far is to call ``` hasattr(myObj, '__iter__') ``` But I am not sure how fool-proof this is.
In Python <= 2.5, you can't and shouldn't - iterable was an "informal" interface. But since Python 2.6 and 3.0 you can leverage the new ABC (abstract base class) infrastructure along with some builtin ABCs which are available in the collections module: ``` from collections import Iterable class MyObject(object): ...
In Python, how do I determine if an object is iterable?
1,952,464
566
2009-12-23T12:13:55Z
4,136,141
13
2010-11-09T16:40:45Z
[ "python", "iterable" ]
Is there a method like `isiterable`? The only solution I have found so far is to call ``` hasattr(myObj, '__iter__') ``` But I am not sure how fool-proof this is.
The best solution I've found so far: `hasattr(obj, '__contains__')` which basically checks if the object implements the `in` operator. **Advantages** (none of the other solutions has all three): * it is an expression (works as a **lambda**, as opposed to the **try...catch** variant) * it is (should be) implemented ...
In Python, how do I determine if an object is iterable?
1,952,464
566
2009-12-23T12:13:55Z
36,407,550
8
2016-04-04T16:04:01Z
[ "python", "iterable" ]
Is there a method like `isiterable`? The only solution I have found so far is to call ``` hasattr(myObj, '__iter__') ``` But I am not sure how fool-proof this is.
I'd like to shed a little bit more light on the interplay of `iter`, `__iter__` and `__getitem__` and what happens behind the curtains. Armed with that knowledge, you will be able to understand why the best you can do is ``` try: iter(maybe_iterable) print('iteration will probably work') except TypeError: ...
permutations of two lists in python
1,953,194
12
2009-12-23T14:44:12Z
1,953,216
8
2009-12-23T14:50:01Z
[ "python" ]
I have two lists like: ``` list1 = ['square','circle','triangle'] list2 = ['red','green'] ``` How can I create all permutations of these lists, like this: ``` [ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle', 'trianglered', 'trianglegreen', ...
How about ``` [x + y for x in list1 for y in list2] + [y + x for x in list1 for y in list2] ``` Example IPython interaction: ``` In [3]: list1 = ['square', 'circle', 'triangle'] In [4]: list2 = ['red', 'green'] In [5]: [x + y for x in list1 for y in list2] + [y + x for x in list1 for y in list2] Out[5]: ['squarer...
permutations of two lists in python
1,953,194
12
2009-12-23T14:44:12Z
1,953,229
34
2009-12-23T14:52:37Z
[ "python" ]
I have two lists like: ``` list1 = ['square','circle','triangle'] list2 = ['red','green'] ``` How can I create all permutations of these lists, like this: ``` [ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle', 'trianglered', 'trianglegreen', ...
You want the **[`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product)** method, which will give you the **[Cartesian product](http://en.wikipedia.org/wiki/Cartesian%5Fproduct)** of both lists. ``` >>> import itertools >>> a = ['foo', 'bar', 'baz'] >>> b = ['x', 'y', 'z', 'w'] >>> for r...
permutations of two lists in python
1,953,194
12
2009-12-23T14:44:12Z
1,953,238
16
2009-12-23T14:54:41Z
[ "python" ]
I have two lists like: ``` list1 = ['square','circle','triangle'] list2 = ['red','green'] ``` How can I create all permutations of these lists, like this: ``` [ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle', 'trianglered', 'trianglegreen', ...
``` >>> import itertools >>> map(''.join, itertools.chain(itertools.product(list1, list2), itertools.product(list2, list1))) ['squarered', 'squaregreen', 'circlered', 'circlegreen', 'trianglered', 'trianglegreen', 'redsquare', 'redcircle', 'redtriangle', 'greensquare', 'greencircle', 'greentriangle'] ```
Retrieving doubly raised exceptions original stack trace in python
1,953,237
4
2009-12-23T14:54:30Z
1,953,591
11
2009-12-23T15:54:34Z
[ "python", "exception" ]
If I have a scenario where an exception is raised, caught, then raised again inside the except: block, is there a way to capture the initial stack frame from which it was raised? The stack-trace that gets printed as python exits describes the place where the exception is raised a second time. Is there a way to raise t...
It's a common mistake to re-raise an exception by specifying the exception instance again, like this: ``` except Exception, ex: # do something raise ex ``` This strips the original traceback info and starts a new one. What you should do instead is this, without explicitly specifying the exception (i.e. use ...
Get html output from python code
1,953,649
5
2009-12-23T16:03:48Z
1,953,685
8
2009-12-23T16:09:15Z
[ "python", "html" ]
I have dictionary and would like to produce html page where will be drawn simple html table with keys and values. How it can be done from python code?
``` output = "<html><body><table>" for key in your_dict: output += "<tr><td>%s</td><td>%s</td></tr>" % (key, your_dict[key]) output += "</table></body></html> print output ```
Python, PyTables, Java - tying all together
1,953,731
24
2009-12-23T16:14:12Z
1,954,175
13
2009-12-23T17:27:12Z
[ "java", "python", "architecture", "hdf5", "pytables" ]
# Question in nutshell What is the best way to get Python and Java to play nice with each other? # More detailed explanation I have a somewhat complicated situation. I'll try my best to explain both in pictures and words. Here's the current system architecture: ![Current system architecture](http://i50.tinypic.com/...
This is an epic question, and there are lots of considerations. Since you didn't mention any specific performance or architectural constraints, I'll try and offer the best well-rounded suggestions. The initial plan of using PyTables as an intermediary layer between your other elements and the datafiles seems solid. Ho...
Accessing XMLNS attribute with Python Elementree?
1,953,761
11
2009-12-23T16:19:07Z
1,954,382
7
2009-12-23T18:03:29Z
[ "python", "xml", "elementtree" ]
How can one access NS attributes through using ElementTree? With the following: ``` <data xmlns="http://www.foo.net/a" xmlns:a="http://www.foo.net/a" book="1" category="ABS" date="2009-12-22"> ``` When I try to root.get('xmlns') I get back None, Category and Date are fine, Any help appreciated..
I think `element.tag` is what you're looking for. Note that your example is missing a trailing slash, so it's unbalanced and won't parse. I've added one in my example. ``` >>> from xml.etree import ElementTree as ET >>> data = '''<data xmlns="http://www.foo.net/a" ... xmlns:a="http://www.foo.net/a" ......
Are CPython, IronPython, Jython scripts compatible with each other?
1,953,989
7
2009-12-23T16:56:17Z
1,954,037
10
2009-12-23T17:04:13Z
[ "python", "testing", "ironpython", "jython", "boost-python" ]
I am pretty sure that python scripts will work in all three, but I want to make sure. I have read here and there about editors that can write CPython, Jython, IronPython and I am hoping that I am looking to much into the distinction. My situation is I have 3 different api's that I want to test. Each api performs the s...
The short answer is: Sometimes. Some projects built on top of IronPython may not work with CPython, and some CPython modules that are written in C (e.g. NumPy) will not work with IronPython. On a similar note, while Jython implements the language specification, it has several incompatibilities with CPython (for insta...
Basics of SymPy
1,954,799
4
2009-12-23T19:19:48Z
1,954,913
9
2009-12-23T19:44:06Z
[ "python", "sympy" ]
I am just starting to play with [SymPy](http://www.google.com/search?hl=en&q=site%3Aen.wikipedia.org+sympy&cts=1261570105189&aq=f&oq=&aqi=) and I am a bit surprised by some of its behavior, for instance this is not the results I would expect: ``` >>> import sympy as s >>> (-1)**s.I == s.E**(-1* s.pi) False >>> s.I**s....
From the [FAQ](https://github.com/sympy/sympy/wiki/Faq#why-does-sympy-say-that-two-equal-expressions-are-unequal): **Why does SymPy say that two equal expressions are unequal?** The equality operator (==) tests whether expressions have identical form, not whether they are mathematically equivalent. To make equality ...
How do I access a object's method when the method's name is in a variable?
1,954,840
6
2009-12-23T19:27:41Z
1,954,846
9
2009-12-23T19:29:04Z
[ "python" ]
Say I have a class object named test. test has various methods, one of them is whatever() . I have a variable named method = "whatever" How can I access the method using the variable with test? Thanks!
Get the attribute with `getattr`: ``` method = "whatever" getattr(test, method) ``` You can also call it: ``` getattr(test, method)() ```
Python: which XML parsing library will work out-of-the-box for Python 2.4 and up?
1,954,923
7
2009-12-23T19:45:22Z
1,954,963
8
2009-12-23T19:54:53Z
[ "python", "xml" ]
How can I make sure that my Python script, which will be doing some XML parsing, will Just Work with Python 2.4, 2.5 and 2.6? Specifically, which (if any) XML parsing library is present in, and compatible between, all those versions? **Edit**: the working-out-of-the-box requirement is in place because the XML parsing...
[minidom](http://docs.python.org/library/xml.dom.minidom.html) is available in Python 2.0 and later. However, if I were you, I would strongly consider using [ElementTree](http://effbot.org/downloads/) which is available in Python 2.5 and later. Its syntax is much more pleasant. 2.4 users can reasonably easily downloa...
Deploying Django at alwaysdata.com
1,955,189
9
2009-12-23T20:38:46Z
1,955,401
21
2009-12-23T21:25:41Z
[ "python", "django", "fastcgi" ]
i new on django i tried this but i cant deploy. how can i do ``` #!/usr/bin/python import sys import os base = os.path.dirname(os.path.abspath(__file__)) + '/..' sys.path.append(base) os.environ['DJANGO_SETTINGS_MODULE'] = 'myfirstapp.settings' import django.core.handlers.wsgi application = django.core.handlers.ws...
Here's the [alwaysdata wiki entry](http://wiki.alwaysdata.com/wiki/D%C3%A9ployer_une_application_Django) for setting up Django with fastcgi. Only down-side: it's written in French. Well, I don't speak French, but what it basically says is: 1. Create a directory named `public` in the folder of your django project. 2. ...
How to redirect stderr in Python?
1,956,142
12
2009-12-24T00:46:09Z
1,956,228
14
2009-12-24T01:16:19Z
[ "python", "redirect", "stderr" ]
I would like to log all the output of a Python script. I tried: ``` import sys log = [] class writer(object): def write(self, data): log.append(data) sys.stdout = writer() sys.stderr = writer() ``` Now, if I "print 'something' " it gets logged. But if I make for instance some syntax error, say "print '...
I have a piece of software I wrote for work that captures stderr to a file like so: ``` import sys sys.stderr = open('C:\\err.txt', 'w') ``` so it's definitely possible. I believe your problem is that you are creating two instances of writer. Maybe something more like: ``` import sys class writer(object): log...
How to redirect stderr in Python? Via Python C API?
1,956,407
2
2009-12-24T02:43:48Z
1,956,422
8
2009-12-24T02:51:44Z
[ "python", "c", "stdout", "python-c-api", "io-redirection" ]
This is a combination of my two recent questions: [1] <http://stackoverflow.com/questions/1954494/python-instance-method-in-c> [2] <http://stackoverflow.com/questions/1956142/how-to-redirect-stderr-in-python> I would like to log the output of both stdout and stderr from a python script. The thing I want to ask is...
Just make a module object (you're doing that anyway, if you're using the C API!-) and make it have a suitable `write` function -- that module object will be suitable as the second argument to `PySys_SetObject`. In my answer to your other question I pointed you to `xxmodule.c`, an example file in Python's C sources, wh...
i don't know __iter__ in python,who can give me a good code example
1,956,623
6
2009-12-24T04:08:26Z
1,956,645
17
2009-12-24T04:21:34Z
[ "python", "iterator" ]
my code run wrong ``` class a(object): def __iter(self): return 33 b={'a':'aaa','b':'bbb'} c=a() print b.itervalues() print c.itervalues() ``` Please try to use the code, rather than text, because my English is not very good, thank you
a. Spell it right: **not** ``` def __iter(self): ``` but: ``` def __iter__(self): ``` with `__` before **and** after `iter`. b. Make the body right: **not** ``` return 33 ``` but: ``` yield 33 ``` or return iter([33]) If you `return` a value from `__iter__`, return an iterator (an *iterable*, as in `ret...
Determining version of easy_install/setuptools
1,956,646
22
2009-12-24T04:21:51Z
1,956,683
17
2009-12-24T04:33:43Z
[ "python", "setuptools", "easy-install" ]
I'm trying to install couchapp, which uses easy\_install - and is quite explicit in stating a particular version of easy\_install/setuptools is needed: 0.6c6. I seem to have easy\_install already on my Mac, but there's no command-line arguments to check the version. Instead of just installing a new version over the top...
One way would be to look at the actual source file for easy\_install. Do ``` which easy_install ``` to see where it's located, and then use that path in ``` less path/to/easy_install ``` The second line in my easy\_install script says: ``` # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==0.6c11','console_scripts','easy_i...
Determining version of easy_install/setuptools
1,956,646
22
2009-12-24T04:21:51Z
22,966,614
30
2014-04-09T15:03:37Z
[ "python", "setuptools", "easy-install" ]
I'm trying to install couchapp, which uses easy\_install - and is quite explicit in stating a particular version of easy\_install/setuptools is needed: 0.6c6. I seem to have easy\_install already on my Mac, but there's no command-line arguments to check the version. Instead of just installing a new version over the top...
This seems to get a lot of hits from google, so I thought I'd update for those folks. I was able to do: ``` easy_install --version ``` which produced the output ``` setuptools 3.4.3 ``` I believe this only works for some (newer?) versions of setuptools
How to make Fabric ignore offline hosts in the env.hosts list?
1,956,777
10
2009-12-24T05:06:03Z
2,561,727
14
2010-04-01T15:53:25Z
[ "python", "fabric" ]
This is related to my [previous question](http://stackoverflow.com/questions/1956717/how-to-make-fabric-execution-follow-the-env-hosts-list-order), but a different one. I have the following fabfile: ``` from fabric.api import * host1 = '192.168.200.181' offline_host2 = '192.168.200.199' host3 = '192.168.200.183' en...
According to the [Fabric documentation on warn\_only](http://docs.fabfile.org/0.9.0/usage/env.html#warn-only), > `env.warn_only` "specifies whether or not to warn, instead of abort, when `run`/`sudo`/`local` encounter error conditions. This will not help in the case of a server being down, since the failure occurs du...
How to make Fabric ignore offline hosts in the env.hosts list?
1,956,777
10
2009-12-24T05:06:03Z
23,139,054
12
2014-04-17T16:54:10Z
[ "python", "fabric" ]
This is related to my [previous question](http://stackoverflow.com/questions/1956717/how-to-make-fabric-execution-follow-the-env-hosts-list-order), but a different one. I have the following fabfile: ``` from fabric.api import * host1 = '192.168.200.181' offline_host2 = '192.168.200.199' host3 = '192.168.200.183' en...
As of version 1.4 Fabric has a `--skip-bad-hosts` option that can be set from the command line, or by setting the variable in your fab file. ``` env.skip_bad_hosts = True ``` Documentation for the option is here: <http://docs.fabfile.org/en/latest/usage/fab.html#cmdoption--skip-bad-hosts> Don't forget to explicitly ...
Is it possible to compile a program written in Python?
1,957,054
20
2009-12-24T06:36:18Z
1,957,065
22
2009-12-24T06:39:21Z
[ "python", "compilation" ]
I am new to the Python programming language. I was wondering if it is possible to compile a program written in Python.
I think [Compiling Python Code](http://effbot.org/zone/python-compile.htm) would be a good place to start: > Python source code is automatically > compiled into Python byte code by the > CPython interpreter. Compiled code is > usually stored in PYC (or PYO) files, > and is regenerated when the source is > updated, or ...
Is it possible to compile a program written in Python?
1,957,054
20
2009-12-24T06:36:18Z
1,957,814
7
2009-12-24T10:42:15Z
[ "python", "compilation" ]
I am new to the Python programming language. I was wondering if it is possible to compile a program written in Python.
Python, as a dynamic language, cannot be "compiled" into machine code statically, like C or COBOL can. You'll always need an interpreter to execute the code, which, by definition in the language, is a dynamic operation. You can "translate" source code in bytecode, which is just an intermediate process that the interpr...
Is it possible to compile a program written in Python?
1,957,054
20
2009-12-24T06:36:18Z
1,959,779
7
2009-12-24T21:11:23Z
[ "python", "compilation" ]
I am new to the Python programming language. I was wondering if it is possible to compile a program written in Python.
If you really want, you could always compile with Cython. This will generate C code, which you can then compile with any C compiler such as GCC.
render_to_response gives TemplateDoesNotExist
1,957,089
8
2009-12-24T06:46:25Z
1,957,315
21
2009-12-24T08:08:31Z
[ "python", "django", "django-templates" ]
I am obtaining the path of template using ``` paymenthtml = os.path.join(os.path.dirname(__file__), 'template\\payment.html') ``` and calling it in another application where paymenthtml gets copied to payment\_template ``` return render_to_response(self.payment_template, self.context, RequestContext(self.request)) `...
It seems like Django will only load templates if they're in a directory you define in `TEMPLATE_DIRS`, even if they exist elsewhere. Try this in settings.py: ``` PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) # Other settings... TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, "templates"), ) ``` and then...
render_to_response gives TemplateDoesNotExist
1,957,089
8
2009-12-24T06:46:25Z
4,639,763
11
2011-01-09T14:44:56Z
[ "python", "django", "django-templates" ]
I am obtaining the path of template using ``` paymenthtml = os.path.join(os.path.dirname(__file__), 'template\\payment.html') ``` and calling it in another application where paymenthtml gets copied to payment\_template ``` return render_to_response(self.payment_template, self.context, RequestContext(self.request)) `...
By the way: A tricky thing is, that django throws `TemplateDoesNotExist` even if the rendered template includes a template that doesn't exist - `{% include "some/template.html" %}`... this knowledge has cost me some time and nerves.
why dict objects are unhashable in python?
1,957,396
22
2009-12-24T08:34:01Z
1,957,403
33
2009-12-24T08:36:25Z
[ "python", "dictionary" ]
I mean why cant we put key of dict as dict? that means we can't have dictionary having key as another dictionary...
Short answer: because they are **mutable containers**. If a dict was hashed, its hash would change as you changed its contents.
why dict objects are unhashable in python?
1,957,396
22
2009-12-24T08:34:01Z
8,706,053
10
2012-01-02T22:38:31Z
[ "python", "dictionary" ]
I mean why cant we put key of dict as dict? that means we can't have dictionary having key as another dictionary...
This is easy to deal with. Wrap a dict in a frozenset before you hash it. Then, when you need to use it, convert it back to a dict. ``` >>> unhashable = {'b': 'a', 'a': 'b'} >>> hashable = frozenset(unhashable.items()) >>> unhashable = dict(hashable) >>> unhashable {'a': 'b', 'b': 'a'} ``` Note that dictionary key or...
How to override [] operator
1,957,780
75
2009-12-24T10:35:24Z
1,957,793
102
2009-12-24T10:38:09Z
[ "python", "operator-overloading" ]
What is the name of the method to override the `[]` operator for a class?
You need to use the [`__getitem__` method](http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetitem%5F%5F). ``` >>> class MyClass: ... def __getitem__(self,index): ... return index * 2 ... >>> myobj = MyClass() >>> myobj[3] 6 ``` And if you're going to be setting values you'll need to implemen...
How to override [] operator
1,957,780
75
2009-12-24T10:35:24Z
1,957,795
8
2009-12-24T10:38:25Z
[ "python", "operator-overloading" ]
What is the name of the method to override the `[]` operator for a class?
You are looking for the `__getitem__` method. See <http://docs.python.org/reference/datamodel.html>, section 3.4.6
How to override [] operator
1,957,780
75
2009-12-24T10:35:24Z
1,957,821
24
2009-12-24T10:43:52Z
[ "python", "operator-overloading" ]
What is the name of the method to override the `[]` operator for a class?
To fully overload it you also need to implement the `__setitem__`and `__delitem__` methods. **edit** I almost forgot... if you want to completely emulate a list, you also need `__getslice__, __setslice__ and __delslice__`. There are all documented in <http://docs.python.org/reference/datamodel.html>
Convert sqlalchemy row object to python dict
1,958,219
91
2009-12-24T12:42:34Z
1,958,228
11
2009-12-24T12:45:04Z
[ "python", "sqlalchemy" ]
Is there a simple way to iterate over column name and value pairs? My version of sqlalchemy is 0.5.6 Here is the sample code where I tried using dict(row), but it throws exception , TypeError: 'User' object is not iterable ``` import sqlalchemy from sqlalchemy import * from sqlalchemy.ext.declarative import declarat...
``` for row in resultproxy: row_as_dict = dict(row) ```
Convert sqlalchemy row object to python dict
1,958,219
91
2009-12-24T12:42:34Z
1,960,546
84
2009-12-25T05:20:20Z
[ "python", "sqlalchemy" ]
Is there a simple way to iterate over column name and value pairs? My version of sqlalchemy is 0.5.6 Here is the sample code where I tried using dict(row), but it throws exception , TypeError: 'User' object is not iterable ``` import sqlalchemy from sqlalchemy import * from sqlalchemy.ext.declarative import declarat...
I couldn't get a good answer so I use this: ``` def row2dict(row): d = {} for column in row.__table__.columns: d[column.name] = str(getattr(row, column.name)) return d ``` Edit: if above function is too long and not suited for some tastes here is a one liner (python 2.7+) ``` row2dict = lambda r...
Convert sqlalchemy row object to python dict
1,958,219
91
2009-12-24T12:42:34Z
2,454,618
13
2010-03-16T13:24:01Z
[ "python", "sqlalchemy" ]
Is there a simple way to iterate over column name and value pairs? My version of sqlalchemy is 0.5.6 Here is the sample code where I tried using dict(row), but it throws exception , TypeError: 'User' object is not iterable ``` import sqlalchemy from sqlalchemy import * from sqlalchemy.ext.declarative import declarat...
``` from sqlalchemy.orm import class_mapper def asdict(obj): return dict((col.name, getattr(obj, col.name)) for col in class_mapper(obj.__class__).mapped_table.c) ```
Convert sqlalchemy row object to python dict
1,958,219
91
2009-12-24T12:42:34Z
10,370,224
102
2012-04-29T06:31:44Z
[ "python", "sqlalchemy" ]
Is there a simple way to iterate over column name and value pairs? My version of sqlalchemy is 0.5.6 Here is the sample code where I tried using dict(row), but it throws exception , TypeError: 'User' object is not iterable ``` import sqlalchemy from sqlalchemy import * from sqlalchemy.ext.declarative import declarat...
You may access the internal `__dict__` of a SQLAlchemy object, like the following:: ``` for u in session.query(User).all(): print u.__dict__ ```
Convert sqlalchemy row object to python dict
1,958,219
91
2009-12-24T12:42:34Z
21,029,850
7
2014-01-09T19:53:55Z
[ "python", "sqlalchemy" ]
Is there a simple way to iterate over column name and value pairs? My version of sqlalchemy is 0.5.6 Here is the sample code where I tried using dict(row), but it throws exception , TypeError: 'User' object is not iterable ``` import sqlalchemy from sqlalchemy import * from sqlalchemy.ext.declarative import declarat...
rows have an `_asdict()` function which gives a dict ``` In [8]: r1 = db.session.query(Topic.name).first() In [9]: r1 Out[9]: (u'blah') In [10]: r1.name Out[10]: u'blah' In [11]: r1._asdict() Out[11]: {'name': u'blah'} ```
Convert sqlalchemy row object to python dict
1,958,219
91
2009-12-24T12:42:34Z
24,748,320
7
2014-07-15T00:47:36Z
[ "python", "sqlalchemy" ]
Is there a simple way to iterate over column name and value pairs? My version of sqlalchemy is 0.5.6 Here is the sample code where I tried using dict(row), but it throws exception , TypeError: 'User' object is not iterable ``` import sqlalchemy from sqlalchemy import * from sqlalchemy.ext.declarative import declarat...
as @balki mentioned: The `_asdict()` method can be used if you're querying a specific field because it is returned as a [KeyedTuple](http://docs.sqlalchemy.org/en/rel_0_9/orm/query.html#sqlalchemy.util.KeyedTuple). ``` In [1]: foo = db.session.query(Topic.name).first() In [2]: foo._asdict() Out[2]: {'name': u'blah'} ...
Why are there dummy modules in sys.modules?
1,958,417
13
2009-12-24T13:58:46Z
1,958,474
20
2009-12-24T14:15:36Z
[ "python", "import" ]
Importing the standard "logging" module pollutes sys.modules with a bunch of dummy entries: ``` Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 >>> import sys >>> import logging >>> sorted(x for x in sys.modules.keys() if 'log' in x) ['logging', 'logging.atexit', 'logging.cStringI...
`None` values in `sys.modules` are cached failures of relative lookups. So when you're in package `foo` and you `import sys`, Python looks first for a `foo.sys` module, and if that fails goes to the top-level `sys` module. To avoid having to check the filesystem for `foo/sys.py` again on further relative imports, it s...
Django manytomany signals?
1,958,540
6
2009-12-24T14:38:29Z
1,959,929
8
2009-12-24T22:26:28Z
[ "python", "django", "django-models", "django-signals" ]
Let's say I have such model ``` class Event(models.Model) users_count = models.IntegerField(default=0) users = models.ManyToManyField(User) ``` How would you recommend to update users\_count value if Event add/delete some users ?
If possible in your case, you could introduce `Participation` model which would join Event and User: ``` class Participation(models.Model): user = models.ForeignKey(User) event = models.ForeignKey(Event) class Event(models.Model): users = models.ManyToManyField(User, through='Participation') ``` And hand...
Absolute import failing in subpackage that shadows a stdlib package name
1,959,188
8
2009-12-24T17:46:34Z
1,959,215
9
2009-12-24T17:53:54Z
[ "python", "import" ]
Basically I have a subpackage with the same name as a standard library package ("logging") and I'd like it to be able to absolute-import the standard one no matter how I run it, but this fails when I'm in the parent package. It really looks like either a bug, or an undocumented behaviour of the new "absolute import" s...
`sys.path[0]` is by default `''`, which means "current directory". So if you are sitting in a directory with `logging` in it, that will be chosen first. I ran into this recently, until I realized that I was actually sitting in that directory and that `sys.path` was picking up my current directory FIRST, before looking...
Python scientific notation using D instead of E
1,959,210
8
2009-12-24T17:52:22Z
1,959,239
8
2009-12-24T18:00:58Z
[ "python", "locale", "scientific-notation" ]
Some results file produced by Fortran programs report double precision numbers (in scientific notation) using the letter `D` instead of `E`, for instance: ``` 1.2345D+02 # instead of 1.2345E+02 ``` I need to process huge amounts of this data using Python, and I just realized it cannot read the numbers in the `D` nota...
The simplest way, from your Python program, would be just to add a step before you interpret each entry: ``` >>> val = "1.5698D+03" # 1,569.8 >>> print float(val.replace('D', 'E')) 1569.8 ```
Python scientific notation using D instead of E
1,959,210
8
2009-12-24T17:52:22Z
1,959,312
14
2009-12-24T18:31:11Z
[ "python", "locale", "scientific-notation" ]
Some results file produced by Fortran programs report double precision numbers (in scientific notation) using the letter `D` instead of `E`, for instance: ``` 1.2345D+02 # instead of 1.2345E+02 ``` I need to process huge amounts of this data using Python, and I just realized it cannot read the numbers in the `D` nota...
If you are dealing with lots of data and/or are doing a lot computations with that data, you might consider using the fortran-friendly [numpy](http://numpy.scipy.org/) module which supports double-precision fortran format out of the box. ``` >>> numpy.float('1.5698D+03') 1569.8 ```
Django JSON Serialization with Mixed Django models and a Dictionary
1,959,375
4
2009-12-24T18:53:03Z
1,959,408
10
2009-12-24T19:05:40Z
[ "python", "django", "json", "serialization" ]
I can't seem to find a good way to serialize both Django Models and Python dictionaries together, its pretty common for me to return a json response that looks like ``` { "modified":updated_object, "success":true ... some additional data... } ``` Its simple enough to use either simplejson to serialize a dict or...
Can't you just convert the model instance to a dict, join the other dict and then serialize? ``` from django.forms import model_to_dict dict = model_to_dict(instance) dict.update(dict2) ... Then serialize here ... ``` Don't know about being "better"... :-)
How do you sort a list in Jinja2?
1,959,386
35
2009-12-24T18:56:31Z
1,959,413
10
2009-12-24T19:06:26Z
[ "python", "sorting", "jinja2" ]
I am trying to do this: ``` {% for movie in movie_list | sort(movie.rating) %} ``` But that's not right...the documentation is vague...how do you do this in Jinja2?
Usually we sort the list before giving it to Jinja2. There's no way to specify a key in Jinja's `sort` filter. However, you can always try `{% for movie in movie_list|sort %}`. That's the syntax. You don't get to provide any sort of key information for the sorting. You can also try and write a custom filter for this....
How do you sort a list in Jinja2?
1,959,386
35
2009-12-24T18:56:31Z
5,490,174
66
2011-03-30T17:55:47Z
[ "python", "sorting", "jinja2" ]
I am trying to do this: ``` {% for movie in movie_list | sort(movie.rating) %} ``` But that's not right...the documentation is vague...how do you do this in Jinja2?
As of version 2.6, Jinja2's built-in sort filter allows you to specify an attribute to sort by: ``` {% for movie in movie_list|sort(attribute='rating') %} ``` See <http://jinja.pocoo.org/docs/templates/#sort>
Django-registration, template
1,959,511
15
2009-12-24T19:41:01Z
1,960,085
17
2009-12-24T23:47:51Z
[ "python", "django" ]
where can I find good templates for django-registration? I've found one, but the activation isn't work properly - when user click on activation link he gets: > Hello ! > Check your e-mail to confirm registration. 7 days left. Instead of ~"Activation succesfull/fail".
Some templates can be found here: <http://devdoodles.wordpress.com/2009/02/16/user-authentication-with-django-registration/> ``` $ tree . |-- [ 981] base.html |-- [ 89] index.html `-- [ 544] registration |-- [ 287] activate.html |-- [ 221] activation...
Django-registration, template
1,959,511
15
2009-12-24T19:41:01Z
4,295,551
14
2010-11-28T05:34:22Z
[ "python", "django" ]
where can I find good templates for django-registration? I've found one, but the activation isn't work properly - when user click on activation link he gets: > Hello ! > Check your e-mail to confirm registration. 7 days left. Instead of ~"Activation succesfull/fail".
I found the templates here to be a good starting point: <https://github.com/yourcelf/django-registration-defaults> (Note that you need to a base.html for them to include)
Python list problem
1,959,744
9
2009-12-24T20:57:24Z
1,959,756
13
2009-12-24T21:02:00Z
[ "python", "list" ]
python: ``` m=[[0]*3]*2 for i in range(3): m[0][i]=1 print m ``` I expect that this code should print ``` [[1, 1, 1], [0, 0, 0]] ``` but it prints ``` [[1, 1, 1], [1, 1, 1]] ```
This is by design. When you use multiplication on elements of a list, you are reproducing the references. See [the section "List creation shortcuts" on the Python Programming/Lists wikibook](http://en.wikibooks.org/wiki/Python%5FProgramming/Lists#List%5Fcreation%5Fshortcuts) which goes into detail on the issues with l...
Python if else micro-optimization
1,959,944
3
2009-12-24T22:33:35Z
1,960,000
19
2009-12-24T22:57:06Z
[ "python", "micro-optimization" ]
In pondering optimization of code, I was wondering which was more expensive in python: ``` if x: d = 1 else: d = 2 ``` or ``` d = 2 if x: d = 1 ``` Any thoughts? I like the reduced line count in the second but wondered if reassignment was more costly than the condition switching.
Don't ponder, don't wonder, **measure** -- with `timeit` **at the shell command line** (by far the best, simplest way to use it!). Python 2.5.4 on Mac OSX 10.5 on a laptop...: ``` $ python -mtimeit -s'x=0' 'if x: d=1' 'else: d=2' 10000000 loops, best of 3: 0.0748 usec per loop $ python -mtimeit -s'x=1' 'if x: d=1' 'el...
How does this class implement the "__iter__" method without implementing "next"?
1,960,309
13
2009-12-25T02:35:50Z
1,960,325
9
2009-12-25T02:44:12Z
[ "python", "iterator", "yield" ]
I have the following code in django.template: ``` class Template(object): def __init__(self, template_string, origin=None, name='<Unknown Template>'): try: template_string = smart_unicode(template_string) except UnicodeDecodeError: raise TemplateEncodingError("Templates can ...
That `__iter__`method returns a python **generator** (see the [documentation](http://docs.python.org/tutorial/classes.html#generators)), as it uses the `yield` keyword. The generator will provide the next() method automatically; quoting the documentation: > What makes generators so compact is that the \_\_iter\_\_() a...
How does this class implement the "__iter__" method without implementing "next"?
1,960,309
13
2009-12-25T02:35:50Z
1,960,330
27
2009-12-25T02:47:23Z
[ "python", "iterator", "yield" ]
I have the following code in django.template: ``` class Template(object): def __init__(self, template_string, origin=None, name='<Unknown Template>'): try: template_string = smart_unicode(template_string) except UnicodeDecodeError: raise TemplateEncodingError("Templates can ...
From the [docs](http://docs.python.org/library/stdtypes.html#generator-types): > If a container object’s `__iter__()` > method is implemented as a generator, > it will automatically return an > iterator object (technically, a > generator object) supplying the > `__iter__()` and `next()` methods.
Python JSON serialize a Decimal object
1,960,516
87
2009-12-25T05:00:12Z
1,960,553
9
2009-12-25T05:29:17Z
[ "python", "json" ]
I have a `Decimal('3.9')` as part of an object, and wish to encode this to a JSON string which should look like `{'x': 3.9}`. I don't care about precision on the client side, so a float is fine. Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yiel...
`3.9` can not be exactly represented in IEEE floats, it will always come as `3.8999999999999999`, e.g. try `print repr(3.9)`, you can read more about it here: <http://en.wikipedia.org/wiki/Floating_point> <http://docs.sun.com/source/806-3568/ncg_goldberg.html> So if you don't want float, only option you have to sen...
Python JSON serialize a Decimal object
1,960,516
87
2009-12-25T05:00:12Z
1,960,649
69
2009-12-25T06:43:22Z
[ "python", "json" ]
I have a `Decimal('3.9')` as part of an object, and wish to encode this to a JSON string which should look like `{'x': 3.9}`. I don't care about precision on the client side, so a float is fine. Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yiel...
How about subclassing `json.JSONEncoder`? ``` class DecimalEncoder(json.JSONEncoder): def _iterencode(self, o, markers=None): if isinstance(o, decimal.Decimal): # wanted a simple yield str(o) in the next line, # but that would mean a yield on the line with super(...), # ...
Python JSON serialize a Decimal object
1,960,516
87
2009-12-25T05:00:12Z
3,148,376
110
2010-06-30T10:34:21Z
[ "python", "json" ]
I have a `Decimal('3.9')` as part of an object, and wish to encode this to a JSON string which should look like `{'x': 3.9}`. I don't care about precision on the client side, so a float is fine. Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yiel...
[Simplejson 2.1](http://code.google.com/p/simplejson/) and higher has native support for Decimal type: ``` >>> json.dumps(Decimal('3.9'), use_decimal=True) '3.9' ``` Note that `use_decimal` is `True` by default: ``` def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, ...
Python JSON serialize a Decimal object
1,960,516
87
2009-12-25T05:00:12Z
3,885,198
71
2010-10-07T19:29:03Z
[ "python", "json" ]
I have a `Decimal('3.9')` as part of an object, and wish to encode this to a JSON string which should look like `{'x': 3.9}`. I don't care about precision on the client side, so a float is fine. Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yiel...
I would like to let everyone know that I tried Michał Marczyk's answer on my web server that was running Python 2.6.5 and it worked fine. However, I upgraded to Python 2.7 and it stopped working. I tried to think of some sort of way to encode Decimal objects and this is what I came up with: ``` class DecimalEncoder(j...
Python JSON serialize a Decimal object
1,960,516
87
2009-12-25T05:00:12Z
8,274,307
10
2011-11-25T21:17:24Z
[ "python", "json" ]
I have a `Decimal('3.9')` as part of an object, and wish to encode this to a JSON string which should look like `{'x': 3.9}`. I don't care about precision on the client side, so a float is fine. Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yiel...
I tried switching from simplejson to builtin json for GAE 2.7, and had issues with the decimal. If default returned str(o) there were quotes (because \_iterencode calls \_iterencode on the results of default), and float(o) would remove trailing 0. If default returns an object of a class that inherits from float (or an...
Where does execution resume following an exception?
1,961,158
3
2009-12-25T13:20:11Z
1,961,176
7
2009-12-25T13:33:19Z
[ "c++", "python", "exception" ]
In general, where does program execution resume after an exception has been thrown and caught? Does it resume following the line of code where the exception was thrown, or does it resume following where it's caught? Also, is this behavior consistent across most programming languages?
The code inside the catch block is executed and the original execution continues right after the catch block.
Floating Point Concepts in Python
1,961,394
3
2009-12-25T15:59:51Z
1,961,400
10
2009-12-25T16:01:10Z
[ "python", "floating-point" ]
Why Does -22/10 return -3 in python. Any pointers regarding this will be helpful for me.
Because it's integer division by default. And integer division is rounded towards minus infinity. Take a look: ``` >>> -22/10 -3 >>> -22/10.0 -2.2000000000000002 ``` Positive: ``` >>> 22/10 2 >>> 22/10.0 2.2000000000000002 ``` Regarding the seeming "inaccuracy" of floating point, this is a great article to read: [W...
Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?
1,961,997
47
2009-12-25T21:28:34Z
1,962,076
43
2009-12-25T22:17:40Z
[ "python", "pyqt4", "virtualenv", "pyside" ]
I'm using [Virtualenv](http://pypi.python.org/pypi/virtualenv) with profit on my development environment with `web.py`, `simplejson` and other web oriented packages. I'm going to develop a simple python client using Qt to reuse some Api developed with web.py. Does anybody here had succesfully installed PyQt4 with Vi...
It should be enough to create an empty virtualenv and then copy the contents of the `.../site-packages/PyQt4` directories into it. I suggest to install PyQt4 once globally, make a copy of the directory, uninstall it and then use this trick to create VEs.
Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?
1,961,997
47
2009-12-25T21:28:34Z
4,673,823
7
2011-01-12T20:43:30Z
[ "python", "pyqt4", "virtualenv", "pyside" ]
I'm using [Virtualenv](http://pypi.python.org/pypi/virtualenv) with profit on my development environment with `web.py`, `simplejson` and other web oriented packages. I'm going to develop a simple python client using Qt to reuse some Api developed with web.py. Does anybody here had succesfully installed PyQt4 with Vi...
I asked if it's possible to install PySide from within virtualenv on irc.freenode.net #pyside channel and got positive answer from *hugopl*. So I followed instructions from [PySide Binaries for Microsoft Windows](http://qt-project.org/wiki/PySide_Binaries_Windows) and it worked. The output is below. ``` Z:\virtualenv\...
Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?
1,961,997
47
2009-12-25T21:28:34Z
9,716,100
41
2012-03-15T08:23:36Z
[ "python", "pyqt4", "virtualenv", "pyside" ]
I'm using [Virtualenv](http://pypi.python.org/pypi/virtualenv) with profit on my development environment with `web.py`, `simplejson` and other web oriented packages. I'm going to develop a simple python client using Qt to reuse some Api developed with web.py. Does anybody here had succesfully installed PyQt4 with Vi...
I have the same problem. I use virtualenvwrapper, so I wrote this script to create a link to PyQt in every new virtual environment. Maybe is useful for someone else: ``` #!/bin/bash # This hook is run after a new virtualenv is activated. # ~/.virtualenvs/postmkvirtualenv LIBS=( PyQt4 sip.so ) PYTHON_VERSION=python$(...
Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?
1,961,997
47
2009-12-25T21:28:34Z
22,783,810
7
2014-04-01T10:56:45Z
[ "python", "pyqt4", "virtualenv", "pyside" ]
I'm using [Virtualenv](http://pypi.python.org/pypi/virtualenv) with profit on my development environment with `web.py`, `simplejson` and other web oriented packages. I'm going to develop a simple python client using Qt to reuse some Api developed with web.py. Does anybody here had succesfully installed PyQt4 with Vi...
For those who want to use PyQt4 in a Python 3 virtualenv (on OSX) you first install PyQt4 and SIP (I will use homebrew) ``` $ brew install python3 $ brew install sip --with-python3 $ brew install pyqt --with-python3 ``` Then create your virtual environment ``` $ virtualenv ... ``` Finally symlink (change the versio...
Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?
1,961,997
47
2009-12-25T21:28:34Z
28,850,104
20
2015-03-04T08:51:45Z
[ "python", "pyqt4", "virtualenv", "pyside" ]
I'm using [Virtualenv](http://pypi.python.org/pypi/virtualenv) with profit on my development environment with `web.py`, `simplejson` and other web oriented packages. I'm going to develop a simple python client using Qt to reuse some Api developed with web.py. Does anybody here had succesfully installed PyQt4 with Vi...
Linux debian, python 2.7: * Install python-qt4 globaly: `sudo apt-get install python-qt4` * Create symbolic link of PyQt4 to your virtual env `ln -s /usr/lib/python2.7/dist-packages/PyQt4/ ~/.virtualenvs/myEnv/lib/python2.7/site-packages/` * Create symbolic link of sip.so to your virtual env`ln -s /usr/lib/python2.7/d...
What does '_' do in Django code?
1,962,287
7
2009-12-26T00:04:41Z
1,962,289
21
2009-12-26T00:07:48Z
[ "python", "django", "internationalization", "gettext" ]
Why does this Django code use `_` in front of 'has favicon' ``` has_favicon = models.BooleanField(_('has favicon')) ```
If you look in the import statements, you'll find that they tied \_ to a function that turns stuff into unicode and localizes it by writing: ``` from django.utils.translation import ugettext_lazy as _ ```
What does '_' do in Django code?
1,962,287
7
2009-12-26T00:04:41Z
1,962,290
9
2009-12-26T00:08:07Z
[ "python", "django", "internationalization", "gettext" ]
Why does this Django code use `_` in front of 'has favicon' ``` has_favicon = models.BooleanField(_('has favicon')) ```
`_` is usually a macro/function from gettext, it means the argument is a localized string. this is not limited to Django or Python. in fact gettext is originally a package for C programs, ported to many other languages over the years.
What does '_' do in Django code?
1,962,287
7
2009-12-26T00:04:41Z
1,965,858
9
2009-12-27T12:35:37Z
[ "python", "django", "internationalization", "gettext" ]
Why does this Django code use `_` in front of 'has favicon' ``` has_favicon = models.BooleanField(_('has favicon')) ```
`_` in Django is a convention that is used for localizing texts. It is an alias for ugettext\_lazy. Read [Lazy translation](https://docs.djangoproject.com/en/1.5/topics/i18n/translation/#lazy-translation) in the docs for more info about it.
How do I make a simple file browser in wxPython?
1,962,592
4
2009-12-26T04:02:57Z
1,962,713
8
2009-12-26T06:10:12Z
[ "python", "wxpython" ]
I'm starting to learn both Python and wxPython and as part of the app I'm doing, I need to have a simple browser on the left pane of my app. I'm wondering how do I do it? Or at least point me to the right direction that'll help me more on how to do one. Thanks in advance! EDIT: a sort of side question, how much of wxP...
I think that the [GenericDirCtrl](http://www.wxpython.org/docs/api/wx.GenericDirCtrl-class.html) widget could be of use for you. [This tutorial](http://wiki.wxpython.org/AnotherTutorial) has many examples, among them a simple usage of that widget in a complete script (screenshot pasted below). And I strongly recommend ...
How to get alpha value of a PNG image with PIL?
1,962,795
14
2009-12-26T07:15:36Z
1,963,146
33
2009-12-26T11:06:04Z
[ "python", "image", "png", "python-imaging-library", "transparent" ]
How to detect if a PNG image has transparent alpha channel or not using PIL? ``` img = Image.open('example.png', 'r') has_alpha = img.mode == 'RGBA' ``` With above code we know whether a PNG image has alpha channel not not but how to get the alpha value? I didn't find a 'transparency' key in img.info dictionary as d...
To get the alpha layer of an RGBA image all you need to do is: ``` red, green, blue, alpha = img.split() ``` or ``` alpha = img.split()[-1] ``` And there is a method to set the alpha layer: ``` img.putalpha(alpha) ``` The transparency key is only used to define the transparency index in the palette mode (P). If y...
Selecting rows from a NumPy ndarray
1,962,980
18
2009-12-26T09:14:12Z
1,963,045
13
2009-12-26T10:12:28Z
[ "python", "numpy" ]
I want to select only certain rows from a [NumPy](http://en.wikipedia.org/wiki/NumPy) array based on the value in the second column. For example, this test array has integers from 1 to 10 in the second column. ``` >>> test = numpy.array([numpy.arange(100), numpy.random.randint(1, 11, 100)]).transpose() >>> test[:10, :...
``` test[numpy.logical_or.reduce([test[:,1] == x for x in wanted])] ``` The result should be faster than the original version since NumPy's doing the inner loops instead of Python.
Selecting rows from a NumPy ndarray
1,962,980
18
2009-12-26T09:14:12Z
1,963,113
24
2009-12-26T10:56:50Z
[ "python", "numpy" ]
I want to select only certain rows from a [NumPy](http://en.wikipedia.org/wiki/NumPy) array based on the value in the second column. For example, this test array has integers from 1 to 10 in the second column. ``` >>> test = numpy.array([numpy.arange(100), numpy.random.randint(1, 11, 100)]).transpose() >>> test[:10, :...
The following solution should be faster than Amnon's solution as `wanted` gets larger: ``` wanted_set = set(wanted) # Much faster look up than with lists, for larger lists @numpy.vectorize def selected(elmt): return elmt in wanted_set # Or: selected = numpy.vectorize(wanted_set.__contains__) print test[selected(te...
Time complexity of accessing a Python dict
1,963,507
7
2009-12-26T14:32:01Z
1,963,514
19
2009-12-26T14:36:44Z
[ "python", "hash", "dictionary", "complexity-theory" ]
I am writing a simple Python program. My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic. I use a dictionary to memoize values. That seems to be a bottleneck. The values I'm hashing are tuples of points. Each point is: (x,y), 0 <= x...
See [Time Complexity](http://wiki.python.org/moin/TimeComplexity). The python dict is a hashmap, its worst case is therefore O(n) if the hash function is bad and results in a lot of collisions. However that is a very rare case where every item added has the same hash and so is added to the same chain which for a major ...
Should I make my python code less fool-proof to improve readability?
1,963,556
5
2009-12-26T14:58:19Z
1,963,561
11
2009-12-26T15:01:41Z
[ "python", "coding-style", "readability" ]
I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code. Instead of: ``` class TextServer(object): def __init__(self, text_values): self.text_values = text_values # <more code> # <more methods> ``` I tend to wri...
Here's some good advice on Python idioms from [this page](http://jaynes.colorado.edu/PythonIdioms.html): --- Catch errors rather than avoiding them to avoid cluttering your code with special cases. This idiom is called EAFP ('easier to ask forgiveness than permission'), as opposed to LBYL ('look before you leap'). Th...
Should I make my python code less fool-proof to improve readability?
1,963,556
5
2009-12-26T14:58:19Z
1,963,573
9
2009-12-26T15:08:03Z
[ "python", "coding-style", "readability" ]
I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code. Instead of: ``` class TextServer(object): def __init__(self, text_values): self.text_values = text_values # <more code> # <more methods> ``` I tend to wri...
"Is my python coding style too paranoid? Or is there a way to improve readability while keeping it fool-proof?" Who's the fool you're protecting yourself from? You? Are you worried that you didn't remember the API you wrote? A peer? Are you worried that someone in the next cubicle will actively make an effort to pas...
What exception to raise if wrong number of arguments passed in to **args?
1,964,126
9
2009-12-26T19:23:38Z
1,964,227
9
2009-12-26T20:05:29Z
[ "python", "exception" ]
Suppose in python you have a routine that accepts three named parameters (as \*\*args), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise ? RuntimeError, a specifically created exception, or other ?
Why not just do what python does? ``` >>> abs(1, 2, 3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: abs() takes exactly one argument (3 given) ```
What exception to raise if wrong number of arguments passed in to **args?
1,964,126
9
2009-12-26T19:23:38Z
1,964,247
13
2009-12-26T20:13:25Z
[ "python", "exception" ]
Suppose in python you have a routine that accepts three named parameters (as \*\*args), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise ? RuntimeError, a specifically created exception, or other ?
Remember that you can subclass Python's built-in exception classes (and `TypeError` would surely be the right built-in exception class to raise here -- that's what Python raises if the number of arguments does not match the signature, in normal cases without `*a` or `**k` forms in the signature). I like having every pa...
Crash reporting in Python
1,964,336
6
2009-12-26T20:57:03Z
1,971,394
7
2009-12-28T20:27:30Z
[ "python", "tkinter", "crash-reports" ]
Is there a [crash reporting](http://en.wikipedia.org/wiki/Crash_reporter) framework that can be used for [pure Python Tkinter applications](http://tkdocs.com/tutorial)? Ideally, it should work cross-platform. Practically speaking, this is more of 'exception reporting' since the Python interpreter itself hardly crashes...
Rather than polluting your code with `try..except` everywhere, you should just implement your own except hook by setting `sys.excepthook`. Here is an example: ``` import sys import traceback def install_excepthook(): def my_excepthook(exctype, value, tb): s = ''.join(traceback.format_exception(exctype, va...
What does __contains__ do, what can call __contains__ function
1,964,934
8
2009-12-27T01:49:02Z
1,964,936
8
2009-12-27T01:51:40Z
[ "python" ]
Here is my code: ``` class a(object): d='ddd' def __contains__(self): if self.d:return True b=a() print b.contains('d') # error print contains(b,'d') # error ```
to get your code to do something (although nothing useful): ``` class a(object): d='ddd' def __contains__(self, m): if self.d: return True b=a() >>> 'd' in b True ``` The [docs](http://docs.python.org/reference/datamodel.html#object.%5F%5Fcontains%5F%5F).
What does __contains__ do, what can call __contains__ function
1,964,934
8
2009-12-27T01:49:02Z
1,964,949
17
2009-12-27T02:04:40Z
[ "python" ]
Here is my code: ``` class a(object): d='ddd' def __contains__(self): if self.d:return True b=a() print b.contains('d') # error print contains(b,'d') # error ```
Like all special methods (with "magic names" that begin and end in `__`), [`__contains__`](https://docs.python.org/2/reference/datamodel.html#object.__contains__) is **not** meant to be called directly (except in very specific cases, such as up=calls to the superclass): rather, such methods are called as part of the op...
Calculate time between time-1 to time-2?
1,965,201
6
2009-12-27T04:50:24Z
1,965,229
12
2009-12-27T05:06:59Z
[ "python" ]
``` enter time-1 // eg 01:12 enter time-2 // eg 18:59 calculate: time-1 to time-2 / 12 // i.e time between 01:12 to 18:59 divided by 12 ``` How can it be done in Python. I'm a beginner so I really have no clue where to start. Edited to add: I don't want a timer. Both time-1 and time-2 are entered by the user manual...
The `datetime` and `timedelta` class from the built-in `datetime` module is what you need. ``` from datetime import datetime # Parse the time strings t1 = datetime.strptime('01:12','%H:%M') t2 = datetime.strptime('18:59','%H:%M') # Do the math, the result is a timedelta object delta = (t2 - t1) / 12 print(delta.seco...
Implementing a popularity algorithm in Django
1,965,341
7
2009-12-27T06:13:47Z
1,965,457
9
2009-12-27T07:45:45Z
[ "python", "django", "algorithm", "postgresql" ]
I am creating a site similar to reddit and hacker news that has a database of links and votes. I am implementing hacker news' popularity algorithm and things are going pretty swimmingly until it comes to actually gathering up these links and displaying them. The algorithm is simple: ``` Y Combinator's Hacker News: Pop...
On Hacker News, only the 210 newest stories and 210 most popular stories are paginated (7 pages worth \* 30 stories each). My guess is that the reason for the limit (at least in part) is this problem. Why not drop all the fancy SQL for the most popular stories and just keep a running list instead? Once you've establis...
How can I pass a variable in a decorator to function's argument in a decorated function?
1,965,607
10
2009-12-27T09:42:33Z
1,965,615
20
2009-12-27T09:50:57Z
[ "python", "decorator" ]
I am in progress to learn Python. Hopefully someone points me to correct way. This is what I'd like to do below: ``` def decorate(function): def wrap_function(*args, **kwargs): str = 'Hello!' # This is what I want return function(*args, **kwargs) return wrap_function @decorate def print_mes...
You can't pass it as its own name, but you can add it to the keywords. ``` def decorate(function): def wrap_function(*args, **kwargs): kwargs['str'] = 'Hello!' return function(*args, **kwargs) return wrap_function @decorate def print_message(*args, **kwargs): print(kwargs['str']) ``` Alte...