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
Is there a fast way to generate a dict of the alphabet in Python?
453,576
24
2009-01-17T16:51:34Z
453,596
7
2009-01-17T17:01:01Z
[ "python", "dictionary", "alphabet" ]
I want to generate a dict with the letters of the alphabet as the keys, something like ``` letter_count = {'a': 0, 'b': 0, 'c': 0} ``` what would be a fast way of generating that dict, rather than me having to type it in? Thanks for your help. **EDIT** Thanks everyone for your solutions :) [nosklo's](http://stac...
Here's a compact version, using a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` >>> import string >>> letter_count = dict( (key, 0) for key in string.ascii_lowercase ) >>> letter_count {'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, ...
Is there a fast way to generate a dict of the alphabet in Python?
453,576
24
2009-01-17T16:51:34Z
453,603
10
2009-01-17T17:03:27Z
[ "python", "dictionary", "alphabet" ]
I want to generate a dict with the letters of the alphabet as the keys, something like ``` letter_count = {'a': 0, 'b': 0, 'c': 0} ``` what would be a fast way of generating that dict, rather than me having to type it in? Thanks for your help. **EDIT** Thanks everyone for your solutions :) [nosklo's](http://stac...
``` import string letter_count = dict(zip(string.ascii_lowercase, [0]*26)) ``` or maybe: ``` import string import itertools letter_count = dict(zip(string.lowercase, itertools.repeat(0))) ``` or even: ``` import string letter_count = dict.fromkeys(string.ascii_lowercase, 0) ``` The preferred solution might be a di...
Is there a fast way to generate a dict of the alphabet in Python?
453,576
24
2009-01-17T16:51:34Z
453,766
8
2009-01-17T18:19:27Z
[ "python", "dictionary", "alphabet" ]
I want to generate a dict with the letters of the alphabet as the keys, something like ``` letter_count = {'a': 0, 'b': 0, 'c': 0} ``` what would be a fast way of generating that dict, rather than me having to type it in? Thanks for your help. **EDIT** Thanks everyone for your solutions :) [nosklo's](http://stac...
If you plan to use it for counting, I suggest the following: ``` import collections d = collections.defaultdict(int) ```
Is there a fast way to generate a dict of the alphabet in Python?
453,576
24
2009-01-17T16:51:34Z
453,785
43
2009-01-17T18:36:15Z
[ "python", "dictionary", "alphabet" ]
I want to generate a dict with the letters of the alphabet as the keys, something like ``` letter_count = {'a': 0, 'b': 0, 'c': 0} ``` what would be a fast way of generating that dict, rather than me having to type it in? Thanks for your help. **EDIT** Thanks everyone for your solutions :) [nosklo's](http://stac...
I find this solution more elegant: ``` import string d = dict.fromkeys(string.ascii_lowercase, 0) ```
Does Django development provide a truly flexible 3 layer architecture?
454,443
3
2009-01-18T01:20:33Z
454,539
9
2009-01-18T02:41:38Z
[ "python", "django", "model-view-controller", "orm" ]
A few weeks ago I asked the question *"Is a PHP, Python, PostgreSQL design suitable for a non-web business application?"* <http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application> A lot of the answers recommended skipping the **PHP** piece and using **Django** to...
You seem to be saying that choosing Django would prevent you from using a more heterogenous solution later. This isn't the case. Django provides a number of interesting connections between the layers, and using Django for all the layers lets you take advantage of those connections. For example, using the Django ORM mea...
Does Django development provide a truly flexible 3 layer architecture?
454,443
3
2009-01-18T01:20:33Z
454,608
7
2009-01-18T03:48:18Z
[ "python", "django", "model-view-controller", "orm" ]
A few weeks ago I asked the question *"Is a PHP, Python, PostgreSQL design suitable for a non-web business application?"* <http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application> A lot of the answers recommended skipping the **PHP** piece and using **Django** to...
Django will happily let you use whatever libraries you want for whatever you want to use them for -- you want a different ORM, use it, you want a different template engine, use it, and so on -- but is designed to provide a common default stack used by many interoperable applications. In other words, if you swap out an ...
How do I re.search or re.match on a whole file without reading it all into memory?
454,456
19
2009-01-18T01:27:16Z
454,589
39
2009-01-18T03:24:46Z
[ "python", "regex", "performance", "file" ]
I want to be able to run a regular expression on an entire file, but I'd like to be able to not have to read the whole file into memory at once as I may be working with rather large files in the future. Is there a way to do this? Thanks! **Clarification:** I cannot read line-by-line because it can span multiple lines.
You can use mmap to map the file to memory. The file contents can then be accessed like a normal string: ``` import re, mmap with open('/var/log/error.log', 'r+') as f: data = mmap.mmap(f.fileno(), 0) mo = re.search('error: (.*)', data) if mo: print "found error", mo.group(1) ``` This also works for big fi...
Find an Image within an Image
454,498
4
2009-01-18T02:07:16Z
454,536
7
2009-01-18T02:40:21Z
[ "java", "python", "image" ]
I am looking for the best way to detect an image within another image. I have a small image and would like to find the location that it appears within a larger image - which will actually be screen captures. Conceptually, it is like a 'Where's Waldo?' sort of search in the larger image. Are there any efficient/quick w...
Wikipedia has an article on [Template Matching](http://en.wikipedia.org/wiki/Template_matching), with sample code. (While that page doesn't handle changed scales, it has links to other styles of matching, for example [Scale invariant feature transform](http://en.wikipedia.org/wiki/Scale-invariant_feature_transform))
How can I make a list in Python like (0,6,12, .. 144)?
454,566
3
2009-01-18T03:04:43Z
454,578
20
2009-01-18T03:11:14Z
[ "python", "list" ]
I am not sure, whether I should use for -loop. Perhaps, like ``` for i in range(145): by 6: //mistake here? print i ```
``` for i in range(0,150,6): print i ``` if you are stepping by a constant
Pythonic macro syntax
454,648
18
2009-01-18T04:22:27Z
483,447
10
2009-01-27T13:48:47Z
[ "python", "syntax", "macros" ]
I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component. My problem is that I can't come up with a pythonic macro definition s...
After thinking about it a while a few days ago, and coming up with nothing worth posting, I came back to it now and came up with some syntax I rather like, because it nearly looks like python: ``` macro PrintMacro: syntax: "print", OneOrMore(Var(), name='vars') return Printnl(vars, None) ``` * Make all the m...
Python get proper line ending
454,725
38
2009-01-18T06:01:14Z
454,731
13
2009-01-18T06:07:20Z
[ "python", "line-endings" ]
Is there an easy way to get the type of line ending that the current operating system uses?
Oh, I figured it out. Apparently, [PEP-278](http://www.python.org/dev/peps/pep-0278/) states the following: > Any line ending in the input file will be seen as a '\n' in Python, so little other code has to change to handle universal newlines.
Python get proper line ending
454,725
38
2009-01-18T06:01:14Z
454,809
61
2009-01-18T08:21:16Z
[ "python", "line-endings" ]
Is there an easy way to get the type of line ending that the current operating system uses?
If you are operating on a file that you opened in text mode, then you are correct that line breaks all show up as '`\n`'. Otherwise, you are looking for [`os.linesep`](http://docs.python.org/library/os.html) . From <http://docs.python.org/library/os.html>: > os.**linesep** > > The string used to separate (or, rather,...
No module named MySQLdb
454,854
211
2009-01-18T09:13:38Z
454,871
39
2009-01-18T09:25:58Z
[ "python", "django" ]
I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.
`mysqldb` is a module for Python that doesn't come pre-installed or with Django. You can download `mysqldb` [here](http://sourceforge.net/projects/mysql-python).
No module named MySQLdb
454,854
211
2009-01-18T09:13:38Z
5,873,259
395
2011-05-03T17:23:47Z
[ "python", "django" ]
I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.
You need to use one of the following commands. Which one depends on what OS and software you have and use. 1. **easy\_install mysql-python** (mix os) 2. **pip install mysql-python** (mix os) 3. **apt-get install python-mysqldb** (Linux Ubuntu, ...) 4. **cd /usr/ports/databases/py-MySQLdb && make install clean** (FreeB...
No module named MySQLdb
454,854
211
2009-01-18T09:13:38Z
5,999,414
24
2011-05-14T02:17:49Z
[ "python", "django" ]
I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.
Ubuntu: ``` sudo apt-get install python-mysqldb ```
No module named MySQLdb
454,854
211
2009-01-18T09:13:38Z
25,475,877
40
2014-08-24T20:11:47Z
[ "python", "django" ]
I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.
...and remember there is **no MySQLdb for python3.x** (I know the question is about python2.x but google rates this post quite high) --- **EDIT:** As stated in the comments, there's a MySQLdb's fork that adds Python 3 support: [github.com/PyMySQL/mysqlclient-python](http://github.com/PyMySQL/mysqlclient-python)
Advice on Python/Django and message queues
454,944
40
2009-01-18T10:42:53Z
455,024
13
2009-01-18T11:54:03Z
[ "python", "django", "message-queue" ]
I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons. Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django ...
So far I have found no "nice" solution for this. I have some more strict soft realtime requirements (taking a picture from a cardboard box being labeled) so probably one of the approaches is fast enough for you. I assume emails can wait for a few minutes. * A "todo list" in the database processed by a cron job. * A "t...
Advice on Python/Django and message queues
454,944
40
2009-01-18T10:42:53Z
456,593
23
2009-01-19T05:16:07Z
[ "python", "django", "message-queue" ]
I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons. Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django ...
In your specific case, where it's just an email queue, I wold take the easy way out and use [django-mailer](http://code.google.com/p/django-mailer/). As a nice side bonues there are other pluggable projects that are smart enough to take advantage of django-mailer when they see it in the stack. As for more general queu...
Using an ordered dict as object dictionary in python
455,059
8
2009-01-18T12:33:03Z
455,087
8
2009-01-18T12:59:34Z
[ "python", "ordereddictionary" ]
I don't know why this doesn't work: I'm using the [odict](http://dev.pocoo.org/hg/sandbox/raw-file/tip/odict.py) class from [PEP 372](http://www.python.org/dev/peps/pep-0372/), but I want to use it as a `__dict__` member, i.e.: ``` class Bag(object): def __init__(self): self.__dict__ = odict() ``` But fo...
The closest answer to your question that I can find is at <http://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html>. Basically, if `__dict__` is not an actual `dict()`, then it is ignored, and attribute lookup fails. The alternative for this is to use the odict as a member, and override the getitem a...
Break on exception in pydev
455,552
40
2009-01-18T17:39:09Z
455,556
16
2009-01-18T17:43:29Z
[ "python", "eclipse", "debugging", "exception", "pydev" ]
Is it possible to get the pydev debugger to break on exception?
~~On **any** exception?~~ If my memory serves me right, in PyDev (in Eclipse) this is possible. --- **EDIT:** went through it again, checked [pdb documentation](http://docs.python.org/library/pdb.html), can't find a way to set an exception breakpoint. If I may suggest a really crude workaround, but if you must, you...
Break on exception in pydev
455,552
40
2009-01-18T17:39:09Z
6,655,894
35
2011-07-11T20:09:05Z
[ "python", "eclipse", "debugging", "exception", "pydev" ]
Is it possible to get the pydev debugger to break on exception?
This was added by the PyDev author, under Run > Manage Python Exception Breakpoints
JSON datetime between Python and JavaScript
455,580
331
2009-01-18T17:51:11Z
455,863
21
2009-01-18T20:51:42Z
[ "javascript", "python", "json" ]
I want to send a datetime.datetime object in serialized form from Python using [JSON](http://en.wikipedia.org/wiki/JSON) and de-serialize in JavaScript using JSON. What is the best way to do this?
If you're certain that only Javascript will be consuming the JSON, I prefer to pass Javascript `Date` objects directly. The `ctime()` method on `datetime` objects will return a string that the Javascript Date object can understand. ``` import datetime date = datetime.datetime.today() json = '{"mydate":new Date("%s")}...
JSON datetime between Python and JavaScript
455,580
331
2009-01-18T17:51:11Z
456,032
66
2009-01-18T22:26:56Z
[ "javascript", "python", "json" ]
I want to send a datetime.datetime object in serialized form from Python using [JSON](http://en.wikipedia.org/wiki/JSON) and de-serialize in JavaScript using JSON. What is the best way to do this?
For cross language projects I found out that strings containing [RfC 3339](http://www.ietf.org/rfc/rfc3339.txt) dates are the best way to go. A RfC 3339 date looks like this: ``` 1985-04-12T23:20:50.52Z ``` I think most of the format is obvious. The only somewhat unusual thing may be the "Z" at the end. It stands f...
JSON datetime between Python and JavaScript
455,580
331
2009-01-18T17:51:11Z
2,680,060
347
2010-04-21T03:09:43Z
[ "javascript", "python", "json" ]
I want to send a datetime.datetime object in serialized form from Python using [JSON](http://en.wikipedia.org/wiki/JSON) and de-serialize in JavaScript using JSON. What is the best way to do this?
You can add the 'default' parameter to json.dumps to handle this: ``` date_handler = lambda obj: ( obj.isoformat() if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date) else None ) json.dumps(datetime.datetime.now(), default=date_handler) '"2010-04-20T20:08:21.634121"' ``` Which is [...
JSON datetime between Python and JavaScript
455,580
331
2009-01-18T17:51:11Z
3,049,307
46
2010-06-15T21:45:25Z
[ "javascript", "python", "json" ]
I want to send a datetime.datetime object in serialized form from Python using [JSON](http://en.wikipedia.org/wiki/JSON) and de-serialize in JavaScript using JSON. What is the best way to do this?
Using `json`, you can subclass JSONEncoder and override the default() method to provide your own custom serializers: ``` import json import datetime class DateTimeJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return obj.isoformat() else: ...
JSON datetime between Python and JavaScript
455,580
331
2009-01-18T17:51:11Z
3,235,787
29
2010-07-13T09:26:57Z
[ "javascript", "python", "json" ]
I want to send a datetime.datetime object in serialized form from Python using [JSON](http://en.wikipedia.org/wiki/JSON) and de-serialize in JavaScript using JSON. What is the best way to do this?
Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library `json` module. This needs Python >= 2.6 since the `%f` format code in the datetime.datetime.strptime() format string is only supported in since then. For Python 2.5 support, dro...
JSON datetime between Python and JavaScript
455,580
331
2009-01-18T17:51:11Z
6,130,825
52
2011-05-25T20:55:37Z
[ "javascript", "python", "json" ]
I want to send a datetime.datetime object in serialized form from Python using [JSON](http://en.wikipedia.org/wiki/JSON) and de-serialize in JavaScript using JSON. What is the best way to do this?
I've worked it out. Let's say you have a Python datetime object, *d*, created with datetime.now(). Its value is: ``` datetime.datetime(2011, 5, 25, 13, 34, 5, 787000) ``` You can serialize it to JSON as an ISO 8601 datetime string: ``` import json json.dumps(d.isoformat()) ``` The example datetime object would...
JSON datetime between Python and JavaScript
455,580
331
2009-01-18T17:51:11Z
32,224,522
7
2015-08-26T10:45:12Z
[ "javascript", "python", "json" ]
I want to send a datetime.datetime object in serialized form from Python using [JSON](http://en.wikipedia.org/wiki/JSON) and de-serialize in JavaScript using JSON. What is the best way to do this?
Late in the game... :) A very simple solution is to patch the json module default. For example: ``` import json import datetime json.JSONEncoder.default = lambda self,obj: (obj.isoformat() if isinstance(obj, datetime.datetime) else None) ``` Now, you can use **json.dumps()** as if it had always supported datetime.....
Limiting floats to two decimal points
455,612
610
2009-01-18T18:16:41Z
455,634
687
2009-01-18T18:23:53Z
[ "python", "floating-point", "precision" ]
I want `a` to be rounded to *13.95*. ``` >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 ``` The [`round`](https://docs.python.org/2/library/functions.html#round) function does not work the way I expected.
You are running into the old problem with floating point numbers that all numbers cannot be represented. The command line is just showing you the full floating point form from memory. In floating point your rounded version is the same number. Since computers are binary they store floating point numbers as an integer an...
Limiting floats to two decimal points
455,612
610
2009-01-18T18:16:41Z
455,658
36
2009-01-18T18:31:50Z
[ "python", "floating-point", "precision" ]
I want `a` to be rounded to *13.95*. ``` >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 ``` The [`round`](https://docs.python.org/2/library/functions.html#round) function does not work the way I expected.
What you can do is modify the output format: ``` >>> a = 13.95 >>> a 13.949999999999999 >>> print "%.2f" % a 13.95 ```
Limiting floats to two decimal points
455,612
610
2009-01-18T18:16:41Z
455,662
8
2009-01-18T18:33:45Z
[ "python", "floating-point", "precision" ]
I want `a` to be rounded to *13.95*. ``` >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 ``` The [`round`](https://docs.python.org/2/library/functions.html#round) function does not work the way I expected.
It's doing exactly what you told it to do, and working correctly. Read more about [floating point confusion](http://www.lahey.com/float.htm) and maybe try [Decimal](http://docs.python.org/library/decimal.html) objects instead.
Limiting floats to two decimal points
455,612
610
2009-01-18T18:16:41Z
455,678
71
2009-01-18T18:40:03Z
[ "python", "floating-point", "precision" ]
I want `a` to be rounded to *13.95*. ``` >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 ``` The [`round`](https://docs.python.org/2/library/functions.html#round) function does not work the way I expected.
Most numbers cannot be exactly represented in floats. If you want to round the number because that's what your mathematical formula or algorithm requires, then you want to use round. If you just want to restrict the display to a certain precision, then don't even use round and just format it as that string. (If you wan...
Limiting floats to two decimal points
455,612
610
2009-01-18T18:16:41Z
456,343
13
2009-01-19T02:05:53Z
[ "python", "floating-point", "precision" ]
I want `a` to be rounded to *13.95*. ``` >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 ``` The [`round`](https://docs.python.org/2/library/functions.html#round) function does not work the way I expected.
The python tutorial has an appendix called: [Floating Point Arithmetic: Issues and Limitations](http://docs.python.org/tutorial/floatingpoint.html). Read it. It explains what is happening and why python is doing its best. It has even an example that matches yours. Let me quote a bit: > ``` > >>> 0.1 > 0.10000000000000...
Limiting floats to two decimal points
455,612
610
2009-01-18T18:16:41Z
6,539,677
249
2011-06-30T18:53:13Z
[ "python", "floating-point", "precision" ]
I want `a` to be rounded to *13.95*. ``` >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 ``` The [`round`](https://docs.python.org/2/library/functions.html#round) function does not work the way I expected.
There are new format specifications, here: <http://docs.python.org/library/string.html#format-specification-mini-language> You can do the same as: ``` "{0:.2f}".format(13.949999999999999) ``` **Note** that the above returns a string. in order to get as float, simply wrap with `float(...)` ``` float("{0:.2f}".forma...
Limiting floats to two decimal points
455,612
610
2009-01-18T18:16:41Z
18,438,167
62
2013-08-26T06:46:25Z
[ "python", "floating-point", "precision" ]
I want `a` to be rounded to *13.95*. ``` >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 ``` The [`round`](https://docs.python.org/2/library/functions.html#round) function does not work the way I expected.
Try codes below: ``` >>> a = 0.99334 >>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up >>> print a 0.99 ```
Limiting floats to two decimal points
455,612
610
2009-01-18T18:16:41Z
20,512,207
22
2013-12-11T06:37:46Z
[ "python", "floating-point", "precision" ]
I want `a` to be rounded to *13.95*. ``` >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 ``` The [`round`](https://docs.python.org/2/library/functions.html#round) function does not work the way I expected.
With python < 3 (e.g. 2.6 or 2.7), there are two ways to do so. ``` # Option one older_method_string = "%.9f" % numvar # Option two (note ':' before the '.9f') newer_method_string = "{:.9f}".format(numvar) ``` But note that for python versions above 3 (e.g. 3.2 or 3.3), option two is [prefered](http://docs.python.o...
Limiting floats to two decimal points
455,612
610
2009-01-18T18:16:41Z
28,142,318
50
2015-01-25T22:26:58Z
[ "python", "floating-point", "precision" ]
I want `a` to be rounded to *13.95*. ``` >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 ``` The [`round`](https://docs.python.org/2/library/functions.html#round) function does not work the way I expected.
I feel that the simplest approach is to use the `format()` function. For example: ``` a = 13.949999999999999 format(a, '.2f') 13.95 ``` This produces a float number as a string rounded to two decimal points.
Limiting floats to two decimal points
455,612
610
2009-01-18T18:16:41Z
35,117,668
8
2016-01-31T18:33:53Z
[ "python", "floating-point", "precision" ]
I want `a` to be rounded to *13.95*. ``` >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 ``` The [`round`](https://docs.python.org/2/library/functions.html#round) function does not work the way I expected.
## **tldr;)** The rounding problem at input / output has been **solved by Python 2.7.0** definitively. ``` import random for x in iter(random.random, None): # verify FOREVER fixed :-) assert float(repr(x)) == x # Reversible repr() conversion assert len(repr(round(x, 10))) <= 12 ...
Python 3 development and distribution challenges
455,717
8
2009-01-18T19:01:08Z
455,840
9
2009-01-18T20:38:22Z
[ "python", "version-control", "python-3.x" ]
Suppose I've developed a general-purpose end user utility written in Python. Previously, I had just one version available which was suitable for Python later than version 2.3 or so. It was sufficient to say, "download Python if you need to, then run this script". There was just one version of the script in source contr...
**Edit:** my original answer was based on the state of 2009, with Python 2.6 and 3.0 as the current versions. Now, with Python 2.7 and 3.3, there are other options. In particular, it is now quite feasible to use a single code base for Python 2 and Python 3. See [Porting Python 2 Code to Python 3](http://docs.python.or...
Is there any advantage in using a Python class?
456,001
15
2009-01-18T22:09:07Z
456,008
29
2009-01-18T22:12:04Z
[ "python", "class", "static-methods" ]
I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?
There are none. This is what modules are for: grouping related functions. Using a class full of static methods makes me cringe from Javaitis. The only time I would use a static function is if the function is an integral part of the class. (In fact, I'd probably want to use a class method anyway.)
Is there any advantage in using a Python class?
456,001
15
2009-01-18T22:09:07Z
456,018
11
2009-01-18T22:17:46Z
[ "python", "class", "static-methods" ]
I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?
No. It would be better to make them functions and if they are related, place them into their own module. For instance, if you have a class like this: ``` class Something(object): @staticmethod def foo(x): return x + 5 @staticmethod def bar(x, y): return y + 5 * x ``` Then it would be...
How do I do what strtok() does in C, in Python?
456,084
7
2009-01-18T23:03:45Z
456,089
26
2009-01-18T23:09:34Z
[ "python" ]
I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much. If I have this: ``` A = '1,2,3,4' B = [int(x) for x in A.split(',')] B results in [1, 2, 3, 4] ``` which is what...
How about this: ``` A = '1, 2,,3,4 ' B = [int(x) for x in A.split(',') if x.strip()] ``` x.strip() trims whitespace from the string, which will make it empty if the string is all whitespace. An empty string is "false" in a boolean context, so it's filtered by the if part of the list comprehension.
Can't get Python to import from a different folder
456,481
40
2009-01-19T03:53:35Z
456,491
64
2009-01-19T04:00:15Z
[ "python" ]
I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure: ``` Server -server.py -Models --user.py ``` Here's the contents of server.py: ``` from ...
I believe you need to create a file called `__init__.py` in the Models directory so that python treats it as a module. Then you can do: ``` from Models.user import User ``` You can include code in the `__init__.py` (for instance initialization code that a few different classes need) or leave it blank. But it must be...
Can't get Python to import from a different folder
456,481
40
2009-01-19T03:53:35Z
456,494
18
2009-01-19T04:02:22Z
[ "python" ]
I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure: ``` Server -server.py -Models --user.py ``` Here's the contents of server.py: ``` from ...
You have to create `__init__.py` on the `Models` subfolder. The file may be empty. It defines a package. Then you can do: ``` from Models.user import User ``` Read all about it in python tutorial, [here](http://docs.python.org/tutorial/modules.html#packages). There is also a good article about file organization of ...
Can't get Python to import from a different folder
456,481
40
2009-01-19T03:53:35Z
456,495
7
2009-01-19T04:02:31Z
[ "python" ]
I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure: ``` Server -server.py -Models --user.py ``` Here's the contents of server.py: ``` from ...
You're missing \_\_init\_\_.py. From the Python tutorial: > The \_\_init\_\_.py files are required to > make Python treat the directories as > containing packages; this is done to > prevent directories with a common > name, such as string, from > unintentionally hiding valid modules > that occur later on the module se...
Can't get Python to import from a different folder
456,481
40
2009-01-19T03:53:35Z
457,630
9
2009-01-19T13:51:51Z
[ "python" ]
I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure: ``` Server -server.py -Models --user.py ``` Here's the contents of server.py: ``` from ...
> import user > > u=user.User() #error on this line Because of the lack of \_\_init\_\_ mentioned above, you would expect an ImportError which would make the problem clearer. You don't get one because 'user' is also an existing module in the standard library. Your import statement grabs that one and tries to find the...
Throttling with urllib2
456,649
8
2009-01-19T05:53:58Z
456,668
18
2009-01-19T06:06:17Z
[ "python", "urllib2", "bandwidth-throttling" ]
is it possible to easily cap the kbps when using `urllib2`? If it is, any code examples or resources you could direct me to would be greatly appreciated.
There is the `urlretrieve(url, filename=None, reporthook=None, data=None)` function in the `urllib` module. If you implement the `reporthook`-function/object as either a [token bucket](http://en.wikipedia.org/wiki/Token_bucket), or a leaky bucket, you have your global rate-limit. **EDIT:** Upon closer examination I se...
Class factory in Python
456,672
46
2009-01-19T06:08:16Z
456,731
15
2009-01-19T06:39:00Z
[ "python", "factory" ]
I'm new to Python and need some advice implementing the scenario below. I have two classes for managing domains at two different registrars. Both have the same interface, e.g. ``` class RegistrarA(Object): def __init__(self, domain): self.domain = domain def lookup(self): ... def registe...
Assuming you need separate classes for different registrars (though it's not obvious in your example) your solution looks okay, though **RegistrarA** and **RegistrarB** probably share functionality and could be derived from an [Abstract Base Class](http://docs.python.org/2/library/abc.html). As an alternative to your ...
Class factory in Python
456,672
46
2009-01-19T06:08:16Z
456,747
62
2009-01-19T06:49:03Z
[ "python", "factory" ]
I'm new to Python and need some advice implementing the scenario below. I have two classes for managing domains at two different registrars. Both have the same interface, e.g. ``` class RegistrarA(Object): def __init__(self, domain): self.domain = domain def lookup(self): ... def registe...
I think using a function is fine. The more interesting question is how do you determine which registrar to load? One option is to have an abstract base Registrar class which concrete implementations subclass, then iterate over its `__subclasses__()` calling an `is_registrar_for()` class method: ``` class Registrar(ob...
Class factory in Python
456,672
46
2009-01-19T06:08:16Z
545,383
10
2009-02-13T09:51:01Z
[ "python", "factory" ]
I'm new to Python and need some advice implementing the scenario below. I have two classes for managing domains at two different registrars. Both have the same interface, e.g. ``` class RegistrarA(Object): def __init__(self, domain): self.domain = domain def lookup(self): ... def registe...
In Python you can change the actual class directly: ``` class Domain(object): def __init__(self, domain): self.domain = domain if ...: self.__class__ = RegistrarA else: self.__class__ = RegistrarB ``` And then following will work. ``` com = Domain('test.com') #load RegistrarA com.lookup() `...
AttributeError: 'module' object has no attribute 'model'
456,867
14
2009-01-19T08:19:25Z
456,886
58
2009-01-19T08:32:41Z
[ "python", "django" ]
Can anyone help me please to solve this.. ``` from django.db import models # Create your models here. class Poll(models.model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.Char...
It's called models.Model and not models.model (case sensitive). Fix your Poll model like this - ``` class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') ``` Hope that helps...
Extending python - to swig, not to swig or Cython
456,884
55
2009-01-19T08:32:06Z
456,949
53
2009-01-19T09:00:41Z
[ "python", "c++", "c", "swig", "cython" ]
I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance. With the help of swig you almost don't need to care about arguments etc. Everything works fine. Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PyS...
You should consider Boost.Python if you are not planning to generate bindings for other languages as well with swig. If you have a lot of functions and classes to bind, [Py++](http://sourceforge.net/projects/pygccxml/) is a great tool that automatically generates the needed code to make the bindings. [Pybindgen](http...
Extending python - to swig, not to swig or Cython
456,884
55
2009-01-19T08:32:06Z
456,995
23
2009-01-19T09:20:19Z
[ "python", "c++", "c", "swig", "cython" ]
I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance. With the help of swig you almost don't need to care about arguments etc. Everything works fine. Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PyS...
For sure you will always have a performance gain doing this by hand, but the gain will be very small compared to the effort required to do this. I don't have any figure to give you but I don't recommend this, because you will need to maintain the interface by hand, and this is not an option if your module is large! Yo...
Extending python - to swig, not to swig or Cython
456,884
55
2009-01-19T08:32:06Z
457,099
16
2009-01-19T10:05:52Z
[ "python", "c++", "c", "swig", "cython" ]
I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance. With the help of swig you almost don't need to care about arguments etc. Everything works fine. Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PyS...
Using [Cython](http://cython.org/) is pretty good. You can write your C extension with a Python-like syntax and have it generate C code. Boilerplate included. Since you have the code already in python, you have to do just a few changes to your bottleneck code and C code will be generated from it. Example. `hello.pyx`:...
Extending python - to swig, not to swig or Cython
456,884
55
2009-01-19T08:32:06Z
3,167,276
7
2010-07-02T15:58:44Z
[ "python", "c++", "c", "swig", "cython" ]
I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance. With the help of swig you almost don't need to care about arguments etc. Everything works fine. Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PyS...
An observation: Based on the benchmarking conducted by the pybindgen developers, there is no significant difference between boost.python and swig. I haven't done my own benchmarking to verify how much of this depends on the proper use of the boost.python functionality. Note also that there may be a reason that pybindg...
Extending python - to swig, not to swig or Cython
456,884
55
2009-01-19T08:32:06Z
6,580,735
26
2011-07-05T09:47:58Z
[ "python", "c++", "c", "swig", "cython" ]
I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance. With the help of swig you almost don't need to care about arguments etc. Everything works fine. Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PyS...
SWIG 2.0.4 has introduced a new -builtin option that improves performance. I did some benchmarking using an example program that does a lot of fast calls to a C++ extension. I built the extension using boost.python, PyBindGen, SIP and SWIG with and without the -builtin option. Here are the results (average of 100 runs)...
Cropping pages of a .pdf file
457,207
9
2009-01-19T10:43:23Z
465,901
14
2009-01-21T16:12:44Z
[ "python", "pdf" ]
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
pypdf does what I expect in this area. Using the following script: ``` #!/usr/bin/python # from pyPdf import PdfFileWriter, PdfFileReader input1 = PdfFileReader(file("in.pdf", "rb")) output = PdfFileWriter() numPages = input1.getNumPages() print "document has %s pages." % numPages for i in range(numPages): pag...
What is the best real time plotting widget for wxPython?
457,246
12
2009-01-19T11:00:38Z
457,524
10
2009-01-19T13:04:57Z
[ "python", "wxpython", "wxwidgets" ]
I would like to show a read time graph with one or two curves an up to 50 samples per second using Python and wxPython. The widget should support both Win32 and Linux platforms. Any hints are welcome. Edited to add: I don't need to update the display at 50 fps, but up need to show up to 50 samples of data on both cu...
Here's a sample of a dynamic plotter with wxPython and matplotlib. While not 50 FPS, it draws smoothly and quickly enough for most real-time data views: <http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/> Here's just the code paste: <http://paste.pocoo.org/show/100358/>
What is the best real time plotting widget for wxPython?
457,246
12
2009-01-19T11:00:38Z
7,605,072
8
2011-09-30T01:24:00Z
[ "python", "wxpython", "wxwidgets" ]
I would like to show a read time graph with one or two curves an up to 50 samples per second using Python and wxPython. The widget should support both Win32 and Linux platforms. Any hints are welcome. Edited to add: I don't need to update the display at 50 fps, but up need to show up to 50 samples of data on both cu...
If you want high performance with a minimal code footprint, look no farther than Python's built-in plotting library tkinter. No need to write special C / C++ code or use a large plotting package to get performance much better than 50 fps. ![Screenshot](http://i.stack.imgur.com/CGK8y.png) The following code scrolls a ...
Is there an easily available implementation of erf() for Python?
457,408
36
2009-01-19T12:10:58Z
457,475
20
2009-01-19T12:47:09Z
[ "python", "math" ]
I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included\_functions.html>this but this seems to be part of some much larger package (and it...
I would recommend you download [numpy](http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103) (to have efficiant matrix in python) and [scipy](http://www.scipy.org/) (a Matlab toolbox substitute, which uses numpy). The erf function lies in scipy. ``` >>>from scipy.special import erf >>>help(erf)...
Is there an easily available implementation of erf() for Python?
457,408
36
2009-01-19T12:10:58Z
457,805
39
2009-01-19T14:46:13Z
[ "python", "math" ]
I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included\_functions.html>this but this seems to be part of some much larger package (and it...
I recommend SciPy for numerical functions in Python, but if you want something with no dependencies, here is a function with an error error is less than 1.5 \* 10-7 for all inputs. ``` def erf(x): # save the sign of x sign = 1 if x >= 0 else -1 x = abs(x) # constants a1 = 0.254829592 a2 = -0....
Is there an easily available implementation of erf() for Python?
457,408
36
2009-01-19T12:10:58Z
463,261
7
2009-01-20T21:44:09Z
[ "python", "math" ]
I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included\_functions.html>this but this seems to be part of some much larger package (and it...
A pure python implementation can be found in the mpmath module (http://code.google.com/p/mpmath/) From the doc string: ``` >>> from mpmath import * >>> mp.dps = 15 >>> print erf(0) 0.0 >>> print erf(1) 0.842700792949715 >>> print erf(-1) -0.842700792949715 >>> print erf(inf) 1.0 >>> print erf(-inf) -1.0 ``` For larg...
Is there an easily available implementation of erf() for Python?
457,408
36
2009-01-19T12:10:58Z
6,662,057
44
2011-07-12T09:31:08Z
[ "python", "math" ]
I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included\_functions.html>this but this seems to be part of some much larger package (and it...
Since v.2.7. the standard *math* module contains *erf* function. This should be the easiest way. <http://docs.python.org/2/library/math.html#math.erf>
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
122
2009-01-19T16:30:57Z
458,246
19
2009-01-19T16:40:24Z
[ "python", "matplotlib", "plot" ]
After these instructions in the Python interpreter one gets a window with a plot: ``` from matplotlib.pyplot import * plot([1,2,3]) show() # other code ``` Unfortunately, I don't know how to continue to interactively explore the figure created by `show()` while the program does further calculations. Is it possible a...
It is better to always check with the library you are using if it supports usage in a **non-blocking** way. But if you want a more generic solution, or if there is no other way, you can run anything that blocks in a separated process by using the [`multprocessing`](http://docs.python.org/library/multiprocessing.html) ...
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
122
2009-01-19T16:30:57Z
458,295
112
2009-01-19T16:52:17Z
[ "python", "matplotlib", "plot" ]
After these instructions in the Python interpreter one gets a window with a plot: ``` from matplotlib.pyplot import * plot([1,2,3]) show() # other code ``` Unfortunately, I don't know how to continue to interactively explore the figure created by `show()` while the program does further calculations. Is it possible a...
Use `matplotlib`'s calls that won't block: Using `draw()`: ``` from matplotlib.pyplot import plot, draw, show plot([1,2,3]) draw() print 'continue computation' # at the end call show to ensure window won't close. show() ``` Using interactive mode: ``` from matplotlib.pyplot import plot, ion, show ion() # enables i...
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
122
2009-01-19T16:30:57Z
458,321
8
2009-01-19T17:00:04Z
[ "python", "matplotlib", "plot" ]
After these instructions in the Python interpreter one gets a window with a plot: ``` from matplotlib.pyplot import * plot([1,2,3]) show() # other code ``` Unfortunately, I don't know how to continue to interactively explore the figure created by `show()` while the program does further calculations. Is it possible a...
You may want to read this document in `matplotlib`'s documentation, titled: [Using matplotlib in a python shell](http://matplotlib.sourceforge.net/users/shell.html#using-matplotlib-in-a-python-shell)
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
122
2009-01-19T16:30:57Z
13,361,748
67
2012-11-13T13:40:54Z
[ "python", "matplotlib", "plot" ]
After these instructions in the Python interpreter one gets a window with a plot: ``` from matplotlib.pyplot import * plot([1,2,3]) show() # other code ``` Unfortunately, I don't know how to continue to interactively explore the figure created by `show()` while the program does further calculations. Is it possible a...
Use the keyword 'block' to override the blocking behavior, e.g. ``` from matplotlib.pyplot import show, plot plot(1) show(block=False) # your code ``` to continue your code.
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
122
2009-01-19T16:30:57Z
14,398,396
13
2013-01-18T11:53:33Z
[ "python", "matplotlib", "plot" ]
After these instructions in the Python interpreter one gets a window with a plot: ``` from matplotlib.pyplot import * plot([1,2,3]) show() # other code ``` Unfortunately, I don't know how to continue to interactively explore the figure created by `show()` while the program does further calculations. Is it possible a...
Try ``` from matplotlib.pyplot import * plot([1,2,3]) show(block=False) # other code # [...] # Put show() # at the very end of your script # to make sure Python doesn't bail out # before you finished examining. ``` The [`show()` documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show) says: ...
How do I install an .egg file without easy_install in Windows?
458,311
14
2009-01-19T16:58:10Z
458,339
12
2009-01-19T17:05:36Z
[ "python", "easy-install", "egg" ]
I have Python 2.6 and I want to install easy \_ install module. The problem is that the only available installation package of easy \_ install for Python 2.6 is an .egg file! What should I do?
You could try [this script](http://peak.telecommunity.com/dist/ez_setup.py). ``` #!python """Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py::     from ez_setup import us...
Adding folders to a zip file using python
458,436
31
2009-01-19T17:33:17Z
459,242
10
2009-01-19T21:34:13Z
[ "python", "file", "zip", "folder", "zipfile" ]
I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder. So I want to end up with a zip file with a single folder with files in. I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject. I started out with this...
A zip file has no directory structure, it just has a bunch of pathnames and their contents. These pathnames should be relative to an imaginary root folder (the ZIP file itself). "../" prefixes have no defined meaning in a zip file. Consider you have a file, `a` and you want to store it in a "folder" inside a zip file....
Adding folders to a zip file using python
458,436
31
2009-01-19T17:33:17Z
459,419
30
2009-01-19T22:21:46Z
[ "python", "file", "zip", "folder", "zipfile" ]
I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder. So I want to end up with a zip file with a single folder with files in. I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject. I started out with this...
Ok, after i understood what you want, it is as simple as using the second argument of `zipfile.write`, where you can use whatever you want: ``` import zipfile myZipFile = zipfile.ZipFile("zip.zip", "w" ) myZipFile.write("test.py", "dir\\test.py", zipfile.ZIP_DEFLATED ) ``` creates a zipfile where `test.py` would be e...
Adding folders to a zip file using python
458,436
31
2009-01-19T17:33:17Z
6,511,788
44
2011-06-28T19:05:19Z
[ "python", "file", "zip", "folder", "zipfile" ]
I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder. So I want to end up with a zip file with a single folder with files in. I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject. I started out with this...
You can also use shutil ``` import shutil shutil.make_archive("desired_zipfile_name_no", "zip", "name_of_the_folder_you_want_to_zip") ``` This will put the whole folder in the zip.
Standard way to embed version into python package?
458,550
126
2009-01-19T18:05:54Z
459,185
64
2009-01-19T21:13:57Z
[ "python", "string", "package" ]
Is there a standard way to associate version string with a python package in such way that I could do the following? ``` import foo print foo.version ``` I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in `setup.py` already. Alternative solu...
Not directly an answer to your question, but you should consider naming it `__version__`, not `version`. This is almost a quasi-standard. Many modules in the standard library use `__version__`, and this is also used in [lots](http://www.google.com/codesearch?as_q=__version__&btnG=Search+Code&hl=en&as_lang=python&as_li...
Standard way to embed version into python package?
458,550
126
2009-01-19T18:05:54Z
1,131,751
17
2009-07-15T14:29:04Z
[ "python", "string", "package" ]
Is there a standard way to associate version string with a python package in such way that I could do the following? ``` import foo print foo.version ``` I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in `setup.py` already. Alternative solu...
Though this is probably far too late, there is a slightly simpler alternative to the previous answer: ``` __version_info__ = ('1', '2', '3') __version__ = '.'.join(__version_info__) ``` (And it would be fairly simple to convert auto-incrementing portions of version numbers to a string using `str()`.) Of course, from...
Standard way to embed version into python package?
458,550
126
2009-01-19T18:05:54Z
7,071,358
67
2011-08-15T22:04:35Z
[ "python", "string", "package" ]
Is there a standard way to associate version string with a python package in such way that I could do the following? ``` import foo print foo.version ``` I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in `setup.py` already. Alternative solu...
Here is how I do this. Advantages of the following method: 1. It provides a `__version__` attribute. 2. It provides the standard metadata version. Therefore it will be detected by `pkg_resources` or other tools that parse the package metadata (EGG-INFO and/or PKG-INFO, PEP 0345). 3. It doesn't import your package (or ...
Standard way to embed version into python package?
458,550
126
2009-01-19T18:05:54Z
15,952,533
19
2013-04-11T15:16:03Z
[ "python", "string", "package" ]
Is there a standard way to associate version string with a python package in such way that I could do the following? ``` import foo print foo.version ``` I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in `setup.py` already. Alternative solu...
Many of the existing answers argue that "There doesn't seem to be a standard way" or that a style "is almost a quasi-standard." In fact *there is a standard way* to do this\*: * **[PEP 396](http://www.python.org/dev/peps/pep-0396/): Module Version Numbers** This describes, with rationale, an (admittedly optional) st...
Standard way to embed version into python package?
458,550
126
2009-01-19T18:05:54Z
16,084,844
44
2013-04-18T13:50:57Z
[ "python", "string", "package" ]
Is there a standard way to associate version string with a python package in such way that I could do the following? ``` import foo print foo.version ``` I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in `setup.py` already. Alternative solu...
Here is the best solution I've seen so far and it also explains why: Inside `yourpackage/version.py`: ``` # Store the version here so: # 1) we don't load dependencies by storing it in __init__.py # 2) we can import it in setup.py for the same reason # 3) we can import it into your module module __version__ = '0.12' `...
How do you run your own code alongside Tkinter's event loop?
459,083
64
2009-01-19T20:40:39Z
459,131
79
2009-01-19T20:55:36Z
[ "python", "events", "tkinter" ]
My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move *every moment*. Tkinter, however, hogs the time for its own event loop, and so his code won...
Use the `after` method on the `Tk` object: ``` from tkinter import * root = Tk() def task(): print("hello") root.after(2000, task) # reschedule event in 2 seconds root.after(2000, task) root.mainloop() ``` Here's the declaration and documentation for the `after` method: ``` def after(self, ms, func=None,...
How do you run your own code alongside Tkinter's event loop?
459,083
64
2009-01-19T20:40:39Z
1,835,036
26
2009-12-02T18:55:46Z
[ "python", "events", "tkinter" ]
My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move *every moment*. Tkinter, however, hogs the time for its own event loop, and so his code won...
The solution posted by Bjorn results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to [one place I checked](http://www.mail-archive.com/tkinter-discuss@python.org/msg01808.html), mishandli...
How do you run your own code alongside Tkinter's event loop?
459,083
64
2009-01-19T20:40:39Z
4,836,121
8
2011-01-29T09:35:20Z
[ "python", "events", "tkinter" ]
My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move *every moment*. Tkinter, however, hogs the time for its own event loop, and so his code won...
When writing your own loop, as in the simulation (I assume), you need to call the `update` function which does what the `mainloop` does: updates the window with your changes, but you do it in your loop. ``` def task(): # do something root.update() while 1: task() ```
Filtering by relation count in SQLAlchemy
459,125
6
2009-01-19T20:53:54Z
459,313
11
2009-01-19T21:48:24Z
[ "python", "sql", "database", "sqlalchemy", "pylons" ]
I'm using the SQLAlchemy Python ORM in a Pylons project. I have a class "Project" which has a one to many relationship with another class "Entry". I want to do a query in SQLAlchemy that gives me all of the projects which have one or more entries associated with them. At the moment I'm doing: ``` [project for project ...
Project.entries.any() should work.
BeautifulSoup - modifying all links in a piece of HTML?
459,981
13
2009-01-20T02:52:19Z
459,991
29
2009-01-20T03:02:34Z
[ "python", "beautifulsoup" ]
I need to be able to modify every single link in an HTML document. I know that I need to use the `SoupStrainer` but I'm not 100% positive on how to implement it. If someone could direct me to a good resource or provide a code example, it'd be very much appreciated. Thanks.
Maybe something like this would work? (I don't have a Python interpreter in front of me, unfortunately) ``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('<p>Blah blah blah <a href="http://google.com">Google</a></p>') for a in soup.findAll('a'): a['href'] = a['href'].replace("google", "mysite") resul...
BeautifulSoup - modifying all links in a piece of HTML?
459,981
13
2009-01-20T02:52:19Z
460,002
22
2009-01-20T03:09:49Z
[ "python", "beautifulsoup" ]
I need to be able to modify every single link in an HTML document. I know that I need to use the `SoupStrainer` but I'm not 100% positive on how to implement it. If someone could direct me to a good resource or provide a code example, it'd be very much appreciated. Thanks.
``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('<p>Blah blah blah <a href="http://google.com">Google</a></p>') for a in soup.findAll('a'): a['href'] = a['href'].replace("google", "mysite") print str(soup) ``` This is Lusid's solution, but since he didn't have a Python interpreter in front of him,...
Algorithm to generate spanning set
460,479
10
2009-01-20T08:38:46Z
460,529
11
2009-01-20T09:02:54Z
[ "python", "algorithm" ]
Given this input: [1,2,3,4] I'd like to generate the set of spanning sets: ``` [1] [2] [3] [4] [1] [2] [3,4] [1] [2,3] [4] [1] [3] [2,4] [1,2] [3] [4] [1,3] [2] [4] [1,4] [2] [3] [1,2] [3,4] [1,3] [2,4] [1,4] [2,3] [1,2,3] [4] [1,2,4] [3] [1,3,4] [2] [2,3,4] [1] [1,2,3,4] ``` Every set has all the elements of the or...
This should work, though I haven't tested it enough. ``` def spanningsets(items): if not items: return if len(items) == 1: yield [[items[-1]]] else: for cc in spanningsets(items[:-1]): yield cc + [[items[-1]]] for i in range(len(cc)): yield cc[:i] + [...
Simulating a 'local static' variable in python
460,586
23
2009-01-20T09:32:42Z
460,601
15
2009-01-20T09:39:21Z
[ "python" ]
Consider the following code: ``` def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } ``` This is the easiest way I can think of for simulating a 'local static' var...
Turn it into a decorator. ``` def static_var(var_name, initial_value): def _set_var(obj): setattr(obj, var_name, initial_value) return obj return _set_var @static_var("_cache", {}) def CalcSomething(a): ... ```
Simulating a 'local static' variable in python
460,586
23
2009-01-20T09:32:42Z
460,691
10
2009-01-20T10:10:57Z
[ "python" ]
Consider the following code: ``` def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } ``` This is the easiest way I can think of for simulating a 'local static' var...
Consider writing decorator that will maintain cache and your function won't be contaminated by caching code: ``` def cacheResults(aFunc): '''This decorator funcion binds a map between the tuple of arguments and results computed by aFunc for those arguments''' def cachedFunc(*args): if not hasat...
Simulating a 'local static' variable in python
460,586
23
2009-01-20T09:32:42Z
460,811
44
2009-01-20T10:57:30Z
[ "python" ]
Consider the following code: ``` def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } ``` This is the easiest way I can think of for simulating a 'local static' var...
Turn it into a callable object (since that's what it really is.) ``` class CalcSomething(object): def __init__(self): self._cache = {} def __call__(self, a): if a not in self._cache: self._cache[a] = self.reallyCalc(a) return self._cache[a] def reallyCalc(self, a): ...
Packet sniffing in Python (Windows)
462,439
5
2009-01-20T18:18:33Z
462,447
9
2009-01-20T18:20:59Z
[ "python", "sniffing", "sniffer" ]
What is the best way to sniff network packets using Python? I've heard from several places that the best module for this is a module called Scapy, unfortunately, it makes python.exe crash on my system. I would assume that it's just a problem with how I installed it, except that many other people have told me that it d...
Use [python-libpcap](http://sourceforge.net/projects/pylibpcap/). ``` import pcap p = pcap.pcapObject() dev = pcap.lookupdev() p.open_live(dev, 1600, 0, 100) #p.setnonblock(1) try: for pktlen, data, timestamp in p: print "[%s] Got data: %s" % (time.strftime('%H:%M', ...
Packet sniffing in Python (Windows)
462,439
5
2009-01-20T18:18:33Z
462,497
7
2009-01-20T18:31:15Z
[ "python", "sniffing", "sniffer" ]
What is the best way to sniff network packets using Python? I've heard from several places that the best module for this is a module called Scapy, unfortunately, it makes python.exe crash on my system. I would assume that it's just a problem with how I installed it, except that many other people have told me that it d...
Using [pypcap](http://code.google.com/p/pypcap/): ``` import dpkt, pcap pc = pcap.pcap() # construct pcap object pc.setfilter('icmp') # filter out unwanted packets for timestamp, packet in pc: print dpkt.ethernet.Ethernet(packet) ``` output sample: ``` Ethernet(src='\x00\x03G\xb2M\xe4', dst='\x00\x03G\x06h\x...
Can I get the matrix determinant using Numpy?
462,500
29
2009-01-20T18:32:16Z
462,514
51
2009-01-20T18:35:26Z
[ "python", "numpy" ]
I read in the manual of Numpy that there is function `det(M)` that can calculate the determinant. However, I can't find the `det()` method in Numpy. By the way, I use Python 2.5. There should be no compatibility problems with Numpy.
You can use [`numpy.linalg.det`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.det.html) to compute the determinant of an array: ``` In [1]: import numpy In [2]: M = [[1, 2], [3, 4]] In [3]: print numpy.linalg.det(M) Out[3]: -2.0000000000000004 ```
Can I get the matrix determinant using Numpy?
462,500
29
2009-01-20T18:32:16Z
19,317,237
14
2013-10-11T11:37:57Z
[ "python", "numpy" ]
I read in the manual of Numpy that there is function `det(M)` that can calculate the determinant. However, I can't find the `det()` method in Numpy. By the way, I use Python 2.5. There should be no compatibility problems with Numpy.
For **large arrays** underflow/overflow may occur when using `numpy.linalg.det`, or you may get `inf` or `-inf` as an answer. In many of these cases you can use `numpy.linalg.slogdet` ([see documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.slogdet.html)), which returns: ``` (sign, logdet...
UnicodeEncodeError with BeautifulSoup 3.1.0.1 and Python 2.5.2
463,215
4
2009-01-20T21:33:25Z
463,382
11
2009-01-20T22:24:20Z
[ "python", "encoding", "screen-scraping", "beautifulsoup" ]
With BeautifulSoup 3.1.0.1 and Python 2.5.2, and trying to parse a web page in French. However, as soon as I call findAll, I get the following error: *UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1146: ordinal not in range(128)* Below is the code I am currently running: ``` import url...
Here is another idea. Your terminal is not capable of displaying an unicode string from Python. The interpreter tries to convert it to ASCII first. You should encode it explicitly before printing. I don't know the exact semantics of `soup.findAll()`. But it is probably something like: ``` for t in soup.findAll("table...
How can I type-check variables in Python?
463,604
20
2009-01-20T23:58:45Z
463,630
21
2009-01-21T00:06:11Z
[ "python", "typing", "dynamic-typing" ]
I have a Python function that takes a numeric argument that **must** be an integer in order for it behave correctly. What is the preferred way of verifying this in Python? My first reaction is to do something like this: ``` def isInteger(n): return int(n) == n ``` But I can't help thinking that this is 1) expens...
``` isinstance(n, int) ``` If you need to know whether it's definitely an actual int and not a subclass of int (generally you shouldn't need to do this): ``` type(n) is int ``` this: ``` return int(n) == n ``` isn't such a good idea, as cross-type comparisons can be true - notably `int(3.0)==3.0`
How can I type-check variables in Python?
463,604
20
2009-01-20T23:58:45Z
463,953
17
2009-01-21T02:50:17Z
[ "python", "typing", "dynamic-typing" ]
I have a Python function that takes a numeric argument that **must** be an integer in order for it behave correctly. What is the preferred way of verifying this in Python? My first reaction is to do something like this: ``` def isInteger(n): return int(n) == n ``` But I can't help thinking that this is 1) expens...
Yeah, as Evan said, don't type check. Just try to use the value: ``` def myintfunction(value): """ Please pass an integer """ return 2 + value ``` That doesn't have a typecheck. It is much better! Let's see what happens when I try it: ``` >>> myintfunction(5) 7 ``` That works, because it is an integer. Hm. Le...
Python - Doing absolute imports from a subfolder
463,643
11
2009-01-21T00:10:47Z
463,904
10
2009-01-21T02:15:30Z
[ "python", "python-import" ]
Basically I'm asking the same question as this guy: <http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python> But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doing what they suggested does not work (as ...
``` main.py setup.py app/ -> __init__.py package_a/ -> __init__.py module_a.py package_b/ -> __init__.py module_b.py ``` 1. You run `python main.py`. 2. `main.py` does: `import app.package_a.module_a` 3. `module_a.py` does `import app.package_b.module_b` Alternatively 2 or 3 co...
Django missing translation of some strings. Any idea why?
463,714
7
2009-01-21T00:38:19Z
463,741
8
2009-01-21T00:54:59Z
[ "python", "django", "internationalization", "translation" ]
I have a medium sized Django project, (running on AppEngine if it makes any difference), and have all the strings living in .po files like they should. I'm seeing strange behavior where certain strings just don't translate. They show up in the .po file when I run make\_messages, with the correct file locations marked ...
Ugh. Django, you're killing me. Here's what was happening: <http://blog.e-shell.org/124> For some reason only Django knows, it decided to decorate some of my translations with the comment '# fuzzy'. It seems to have chosen which ones to mark randomly. Anyway, #fuzzy means this: "don't translate this, even though he...
Django missing translation of some strings. Any idea why?
463,714
7
2009-01-21T00:38:19Z
463,928
10
2009-01-21T02:31:43Z
[ "python", "django", "internationalization", "translation" ]
I have a medium sized Django project, (running on AppEngine if it makes any difference), and have all the strings living in .po files like they should. I'm seeing strange behavior where certain strings just don't translate. They show up in the .po file when I run make\_messages, with the correct file locations marked ...
The fuzzy marker is added to the .po file by makemessages. When you have a new string (with no translations), it looks for similar strings, and includes them as the translation, with the fuzzy marker. This means, this is a crude match, so don't display it to the user, but it could be a good start for the human translat...
Using DPAPI with Python?
463,832
13
2009-01-21T01:30:50Z
463,852
8
2009-01-21T01:37:54Z
[ "python", "windows", "security", "encryption", "dpapi" ]
Is there a way to use the DPAPI (Data Protection Application Programming Interface) on Windows XP with Python? I would prefer to use an existing module if there is one that can do it. Unfortunately I haven't been able to find a way with Google or Stack Overflow. **EDIT:** I've taken the example code pointed to by "dF...
I have been using `CryptProtectData` and `CryptUnprotectData` through ctypes, with the code from <http://article.gmane.org/gmane.comp.python.ctypes/420> and it has been working well.
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
42
2009-01-21T02:54:45Z
464,007
7
2009-01-21T03:31:22Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
I have a list/queue of 200 commands that I need to run in a shell on a Linux server. I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. When a process finishes I want the next command to be "popped"...
GNU make (and perhaps other implementations as well) has the -j argument, which governs how many jobs it will run at once. When a job completes, make will start another one.
Parallel processing from a command queue on Linux (bash, python, ruby... whatever)
463,963
42
2009-01-21T02:54:45Z
464,029
41
2009-01-21T03:53:00Z
[ "python", "ruby", "bash", "shell", "parallel-processing" ]
I have a list/queue of 200 commands that I need to run in a shell on a Linux server. I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer. When a process finishes I want the next command to be "popped"...
On the shell, `xargs` can be used to queue parallel command processing. For example, for having always 3 sleeps in parallel, sleeping for 1 second each, and executing 10 sleeps in total do ``` echo {1..10} | xargs -d ' ' -n1 -P3 sh -c 'sleep 1s' _ ``` And it would sleep for 4 seconds in total. If you have a list of n...