title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to determine the variable type in Python?
402,504
607
2008-12-31T07:58:57Z
402,508
9
2008-12-31T08:02:11Z
[ "python", "types", "unsigned", "signed", "16-bit" ]
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.? How do I view it?
``` print type(variable_name) ``` I also highly recommend the [IPython](http://ipython.scipy.org/) interactive interpreter when dealing with questions like this. It lets you type `variable_name?` and will return a whole list of information about the object including the type and the doc string for the type. e.g. ```...
How to determine the variable type in Python?
402,504
607
2008-12-31T07:58:57Z
402,511
20
2008-12-31T08:08:06Z
[ "python", "types", "unsigned", "signed", "16-bit" ]
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.? How do I view it?
The question is somewhat ambiguous -- I'm not sure what you mean by "view". If you are trying to *query* the type of a native Python object, [@atzz](http://stackoverflow.com/questions/402504/how-to-determine-the-variable-type-in-python#402516)'s answer will steer you in the right direction. However, if you are trying ...
How to determine the variable type in Python?
402,504
607
2008-12-31T07:58:57Z
402,515
12
2008-12-31T08:10:54Z
[ "python", "types", "unsigned", "signed", "16-bit" ]
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.? How do I view it?
Do you mean in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) or using [ctypes](http://www.python.org/doc/2.5/lib/module-ctypes.html)? In the first case, you simply cannot - because Python does not have signed/unsigned, 16/32 bit integers. In the second case, you can use `type()`: ``` >>> i...
How to determine the variable type in Python?
402,504
607
2008-12-31T07:58:57Z
402,516
10
2008-12-31T08:12:34Z
[ "python", "types", "unsigned", "signed", "16-bit" ]
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.? How do I view it?
Python doesn't have such types as you describe. There are two types used to represent integral values: `int`, which corresponds to platform's int type in C, and `long`, which is an arbitrary precision integer (i.e. it grows as needed and doesn't have an upper limit). `int`s are silently converted to `long` if an expres...
How to determine the variable type in Python?
402,504
607
2008-12-31T07:58:57Z
402,704
582
2008-12-31T10:43:07Z
[ "python", "types", "unsigned", "signed", "16-bit" ]
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.? How do I view it?
Python doesn't have the same types as C/C++, which appears to be your question. Try this: ``` >>> i = 123 >>> type(i) <type 'int'> >>> type(i) is int True >>> i = 123456789L >>> type(i) <type 'long'> >>> type(i) is long True >>> i = 123.456 >>> type(i) <type 'float'> >>> type(i) is float True ``` The distinction bet...
How to determine the variable type in Python?
402,504
607
2008-12-31T07:58:57Z
18,224,831
9
2013-08-14T06:39:32Z
[ "python", "types", "unsigned", "signed", "16-bit" ]
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.? How do I view it?
It may be little irrelevant. but you can check types of an object with `isinstance(object, type)` as mentioned [here](http://stackoverflow.com/questions/2225038/python-determine-the-type-of-an-object "Object type in python").
How to determine the variable type in Python?
402,504
607
2008-12-31T07:58:57Z
29,113,307
26
2015-03-18T02:48:04Z
[ "python", "types", "unsigned", "signed", "16-bit" ]
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.? How do I view it?
One more way using `__class__`: ``` >>> a = [1, 2, 3, 4] >>> a.__class__ <type 'list'> >>> b = {'key1': 'val1'} >>> b.__class__ <type 'dict'> >>> c = 12 >>> c.__class__ <type 'int'> ```
How to determine the variable type in Python?
402,504
607
2008-12-31T07:58:57Z
32,885,953
55
2015-10-01T11:02:32Z
[ "python", "types", "unsigned", "signed", "16-bit" ]
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.? How do I view it?
It is so simple. You do it like this. ``` print type(variable_name) ```
How to sort a list of objects in Python, based on an attribute of the objects?
403,421
310
2008-12-31T16:41:32Z
403,426
531
2008-12-31T16:42:59Z
[ "python", "sorting", "count" ]
I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like: ``` >>> ut [<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...] ``` Each object has a count: ``` >>> ut[1].count 1L ``` I need to sort the list b...
``` # To sort the list in place... ut.sort(key=lambda x: x.count, reverse=True) # To return a new list, use the sorted() built-in function... newlist = sorted(ut, key=lambda x: x.count, reverse=True) ``` More on [sorting by keys »](http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys)
How to sort a list of objects in Python, based on an attribute of the objects?
403,421
310
2008-12-31T16:41:32Z
403,496
9
2008-12-31T17:10:00Z
[ "python", "sorting", "count" ]
I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like: ``` >>> ut [<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...] ``` Each object has a count: ``` >>> ut[1].count 1L ``` I need to sort the list b...
It looks much like a list of Django ORM model instances. Why not sort them on query like this: ``` ut = Tag.objects.order_by('-count') ```
How to sort a list of objects in Python, based on an attribute of the objects?
403,421
310
2008-12-31T16:41:32Z
403,607
38
2008-12-31T17:48:21Z
[ "python", "sorting", "count" ]
I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like: ``` >>> ut [<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...] ``` Each object has a count: ``` >>> ut[1].count 1L ``` I need to sort the list b...
A way that can be fastest, especially if your list has a lot of records, is to use `operator.attrgetter("count")`. However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then: ``` try: import operator except ImportError: cmpfu...
How to sort a list of objects in Python, based on an attribute of the objects?
403,421
310
2008-12-31T16:41:32Z
403,795
10
2008-12-31T19:00:33Z
[ "python", "sorting", "count" ]
I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like: ``` >>> ut [<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...] ``` Each object has a count: ``` >>> ut[1].count 1L ``` I need to sort the list b...
``` from operator import attrgetter ut.sort(key = attrgetter('count'), reverse = True) ```
How to sort a list of objects in Python, based on an attribute of the objects?
403,421
310
2008-12-31T16:41:32Z
988,728
26
2009-06-12T19:54:58Z
[ "python", "sorting", "count" ]
I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like: ``` >>> ut [<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...] ``` Each object has a count: ``` >>> ut[1].count 1L ``` I need to sort the list b...
Readers should notice that the key= method: ``` ut.sort(key=lambda x: x.count, reverse=True) ``` is many times faster than adding rich comparison operators to the objects. I was surprised to read this (page 485 of "Python in a Nutshell"). You can confirm this by running tests on this little program: ``` #!/usr/bin/e...
Optimization in Python - do's, don'ts and rules of thumb
403,794
8
2008-12-31T18:57:59Z
403,821
12
2008-12-31T19:13:19Z
[ "python", "optimization" ]
Well I was reading this [post](http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/) and then I came across a code which was: ``` jokes=range(1000000) domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)] ``` I thought wouldn't it be better to calculate the value of len(jo...
You're not using [`timeit`](http://docs.python.org/library/timeit.html) correctly: the argument to `-s` (setup) is a statement to be executed once initially, so you're really just testing an empty statement. You want to do ``` $ python -m timeit -s "jokes=range(1000000)" "domain=[(0,(len(jokes)*2)-i-1) for i in range(...
Calling from a parent file in python
403,822
3
2008-12-31T19:14:59Z
403,832
9
2008-12-31T19:20:03Z
[ "python" ]
I have a file called main.py and a file called classes.py main.py contains the application and what's happening while class.py contains some classes. main.py has the following code **main.py** ``` import classes def addItem(text): print text myClass = classes.ExampleClass() ``` And then we have classes.py *...
I couldn't answer this any better than [this post by Alex Martelli](http://mail.python.org/pipermail/python-list/2000-December/059926.html). Basically any way you try to do this will lead to trouble and you are much better off refactoring the code to avoid mutual dependencies between two modules... If you have two mod...
All code in one file
403,934
5
2008-12-31T19:59:29Z
403,944
12
2008-12-31T20:04:33Z
[ "python", "version-control", "project-management" ]
After asking [organising my Python project](http://stackoverflow.com/questions/391879/organising-my-python-project) and then [calling from a parent file in Python](http://stackoverflow.com/questions/403822/calling-from-a-parent-file-in-python) it's occurring to me that it'll be so much easier to put all my code in one ...
If you are planning to use any kind of SCM then you are going to be screwed. Having one file is a guaranteed way to have lots of collisions and merges that will be painstaking to deal with over time. Stick to conventions and break apart your files. If nothing more than to save the guy who will one day have to maintain...
Python program to calculate harmonic series
404,346
4
2009-01-01T00:55:16Z
404,425
12
2009-01-01T02:31:41Z
[ "python", "math" ]
Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...
[@recursive's solution](http://stackoverflow.com/questions/404346/python-program-to-calculate-harmonic-series#404354) is correct for a floating point approximation. If you prefer, you can get the exact answer in Python 3.0 using the fractions module: ``` >>> from fractions import Fraction >>> def calc_harmonic(n): ......
Python program to calculate harmonic series
404,346
4
2009-01-01T00:55:16Z
404,843
17
2009-01-01T10:47:42Z
[ "python", "math" ]
Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...
[@Kiv's answer](http://stackoverflow.com/questions/404346/python-program-to-calculate-harmonic-series#404425) is correct but it is slow for large n if you don't need an infinite precision. It is better to use an [asymptotic formula](http://en.wikipedia.org/wiki/Harmonic_number) in this case: ![asymptotic expansion for...
Determining application path in a Python EXE generated by pyInstaller
404,744
30
2009-01-01T08:50:22Z
404,750
62
2009-01-01T08:53:20Z
[ "python", "executable", "relative-path", "pyinstaller" ]
I have an application that resides in a single .py file. I've been able to get pyInstaller to bundle it successfully into an EXE for Windows. The problem is, the application requires a .cfg file that always sits directly beside the application in the same directory. Normally, I build the path using the following code:...
I found a solution. You need to check if the application is running as a script or as a frozen exe: ``` import os import sys config_name = 'myapp.cfg' # determine if application is a script file or frozen exe if getattr(sys, 'frozen', False): application_path = os.path.dirname(sys.executable) elif __file__: ...
LBYL vs EAFP in Java?
404,795
39
2009-01-01T09:50:56Z
404,999
10
2009-01-01T14:30:19Z
[ "java", "python", "error-handling", "idioms" ]
I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language. LBYL (***L***ook **B**efore **Y**ou **L**eap): ``` def safe_divide_1(x, y): if y == 0: ...
Exceptions are handled more efficiently in Python than in Java, which is at least *partly* why you see that construct in Python. In Java, it's more inefficient (in terms of performance) to use exceptions in that way.
LBYL vs EAFP in Java?
404,795
39
2009-01-01T09:50:56Z
405,220
89
2009-01-01T17:52:24Z
[ "java", "python", "error-handling", "idioms" ]
I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language. LBYL (***L***ook **B**efore **Y**ou **L**eap): ``` def safe_divide_1(x, y): if y == 0: ...
If you are accessing files, EAFP is more reliable than LBYL, because the operations involved in LBYL are not atomic, and the file system might change between the time you look and the time you leap. Actually, the standard name is TOCTOU - Time of Check, Time of Use; bugs caused by inaccurate checking are TOCTOU bugs. ...
LBYL vs EAFP in Java?
404,795
39
2009-01-01T09:50:56Z
408,305
37
2009-01-02T23:31:52Z
[ "java", "python", "error-handling", "idioms" ]
I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language. LBYL (***L***ook **B**efore **Y**ou **L**eap): ``` def safe_divide_1(x, y): if y == 0: ...
In addition to the relative cost of exceptions in Python and Java, keep in mind that there's a difference in philosophy / attitude between them. Java tries to be very strict about types (and everything else), requiring explicit, detailed declarations of class/method signatures. It assumes that you should know, at any p...
Line reading chokes on 0x1A
405,058
12
2009-01-01T15:29:35Z
405,061
26
2009-01-01T15:31:38Z
[ "python", "windows", "binary-data" ]
I have the following file: ``` abcde kwakwa <0x1A> line3 linllll ``` Where `<0x1A>` represents a byte with the hex value of 0x1A. When attempting to read this file in Python as: ``` for line in open('t.txt'): print line, ``` It only reads the first two lines, and exits the loop. The solution seems to be to ope...
0x1A is Ctrl-Z, and DOS historically used that as an end-of-file marker. For example, try using a command prompt, and "type"ing your file. It will only display the content up the Ctrl-Z. Python uses the Windows CRT function \_wfopen, which implements the "Ctrl-Z is EOF" semantics.
Line reading chokes on 0x1A
405,058
12
2009-01-01T15:29:35Z
405,169
8
2009-01-01T17:13:22Z
[ "python", "windows", "binary-data" ]
I have the following file: ``` abcde kwakwa <0x1A> line3 linllll ``` Where `<0x1A>` represents a byte with the hex value of 0x1A. When attempting to read this file in Python as: ``` for line in open('t.txt'): print line, ``` It only reads the first two lines, and exits the loop. The solution seems to be to ope...
[Ned](http://stackoverflow.com/questions/405058/line-reading-chokes-on-0x1a#405061) is of course correct. If your curiosity runs a little deeper, the root cause is backwards compatibility taken to an extreme. Windows is compatible with DOS, which used Ctrl-Z as an optional end of file marker for text files. What you m...
Please advise on Ruby vs Python, for someone who likes LISP a lot
405,165
20
2009-01-01T17:12:12Z
405,188
24
2009-01-01T17:24:30Z
[ "python", "ruby", "lisp" ]
I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature. Which one is closer to LISP: Python or Ruby? I can...
I'd go with Ruby. It's got all kinds of metaprogramming and duck punching hacks that make it really easy to extend. Features like blocks may not seem like much at first, but they make for some really clean syntax if you use them right. Open classes can be debugging hell if you screw them up, but if you're a responsible...
Please advise on Ruby vs Python, for someone who likes LISP a lot
405,165
20
2009-01-01T17:12:12Z
405,206
31
2009-01-01T17:40:13Z
[ "python", "ruby", "lisp" ]
I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature. Which one is closer to LISP: Python or Ruby? I can...
[Peter Norvig](http://norvig.com), [a famous and great lisper](http://norvig.com/paip.html), converted to Python. He wrote the article [Python for Lisp Programmers](http://norvig.com/python-lisp.html), which you might find interesting with its detailed comparison of features. Python looks like executable pseudo-code. ...
Please advise on Ruby vs Python, for someone who likes LISP a lot
405,165
20
2009-01-01T17:12:12Z
405,228
12
2009-01-01T18:00:04Z
[ "python", "ruby", "lisp" ]
I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature. Which one is closer to LISP: Python or Ruby? I can...
Speaking as a "Rubyist", I'd agree with Kiv. The two languages both grant a nice amount of leeway when it comes to programming paradigms, but are also have benefits/shortcomings. I think that the compromises you make either way are a lot about your own programming style and taste. Personally, I think Ruby can read mor...
Please advise on Ruby vs Python, for someone who likes LISP a lot
405,165
20
2009-01-01T17:12:12Z
405,310
8
2009-01-01T19:01:50Z
[ "python", "ruby", "lisp" ]
I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature. Which one is closer to LISP: Python or Ruby? I can...
Both Ruby and Python are fairly distant from the Lisp traditions of immutable data, programs as data, and macros. But Ruby is very nearly a clone of Smalltalk (and I hope will grow more like Smalltalk as the Perlish cruft is deprecated), and Smalltalk, like Lisp, is a language that takes one idea to extremes. Based on ...
Please advise on Ruby vs Python, for someone who likes LISP a lot
405,165
20
2009-01-01T17:12:12Z
405,342
17
2009-01-01T19:23:00Z
[ "python", "ruby", "lisp" ]
I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature. Which one is closer to LISP: Python or Ruby? I can...
**Devils Advocate: Who Cares?** They are both good systems and have an ecosystem of good web frameworks and active developer communities. I'm guessing that you're framing your decision based on the wrong criteria. The question sounds like you're fretting about whether you will hit implementation problems or other diff...
Many instances of a class
405,282
3
2009-01-01T18:47:32Z
405,292
7
2009-01-01T18:52:03Z
[ "python", "class", "object", "multiple-instances" ]
I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be. So, my question: How can I automatically give a name to an object? I was thinking of creating a "Herd" class whi...
Hm, well you normally just stuff all those instances in a list and then iterate over that list if you want to do something with them. If you want to automatically keep track of each instance created you can also make the adding to the list implicit in the class' constructor or create a factory method that keeps track o...
Mysql connection pooling question: is it worth it?
405,352
15
2009-01-01T19:32:29Z
405,914
10
2009-01-02T02:41:50Z
[ "python", "mysql", "sqlalchemy", "connection-pooling" ]
I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using [a library that provides connection pooling](http://www.sqlalchemy.org/) (SQLAlchemy) won't actually help you that much if you enable the connection pool. Does anyone have any experien...
There's no need to worry about residual state on a connection when using SQLA's connection pool, unless your application is changing connectionwide options like transaction isolation levels (which generally is not the case). SQLA's connection pool issues a connection.rollback() on the connection when its checked back i...
Python update object from dictionary
405,489
11
2009-01-01T21:12:51Z
405,492
21
2009-01-01T21:14:32Z
[ "python", "iterable-unpacking" ]
Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables? This is what I intend to do: ``` c = MyClass() c.foo = 123 c.bar = 123 # c.foo == 123 and c.bar == 123 d = {'bar': 456} c.update(d) # c.foo == 123 and c.bar == 456 ``` Something akin to dic...
Have you tried ``` f.__dict__.update( b ) ``` ?
Python update object from dictionary
405,489
11
2009-01-01T21:12:51Z
408,016
24
2009-01-02T21:02:16Z
[ "python", "iterable-unpacking" ]
Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables? This is what I intend to do: ``` c = MyClass() c.foo = 123 c.bar = 123 # c.foo == 123 and c.bar == 123 d = {'bar': 456} c.update(d) # c.foo == 123 and c.bar == 456 ``` Something akin to dic...
there is also another way of doing it by looping through the items in d. this doesn't have the same assuption that they will get stored in `c.__dict__` which isn't always true. ``` d = {'bar': 456} for key,value in d.items(): setattr(c,key,value) ``` or you could write a `update` method as part of `MyClass` so th...
if all in list == something
405,516
13
2009-01-01T21:41:22Z
405,519
13
2009-01-01T21:43:29Z
[ "python", "python-2.6" ]
Using python 2.6 is there a way to check if all the items of a sequence equals a given value, in one statement? ``` [pseudocode] my_sequence = (2,5,7,82,35) if all the values in (type(i) for i in my_sequence) == int: do() ``` instead of, say: ``` my_sequence = (2,5,7,82,35) all_int = True for i in my_sequence:...
Do you mean ``` all( type(i) is int for i in my_list ) ``` ? Edit: Changed to `is`. Slightly faster.
if all in list == something
405,516
13
2009-01-01T21:41:22Z
405,520
34
2009-01-01T21:45:31Z
[ "python", "python-2.6" ]
Using python 2.6 is there a way to check if all the items of a sequence equals a given value, in one statement? ``` [pseudocode] my_sequence = (2,5,7,82,35) if all the values in (type(i) for i in my_sequence) == int: do() ``` instead of, say: ``` my_sequence = (2,5,7,82,35) all_int = True for i in my_sequence:...
Use: ``` all( type(i) is int for i in lst ) ``` Example: ``` In [1]: lst = range(10) In [2]: all( type(i) is int for i in lst ) Out[2]: True In [3]: lst.append('steve') In [4]: all( type(i) is int for i in lst ) Out[4]: False ``` [Edit]. Made cleaner as per comments.
What is a cyclic data structure good for?
405,540
13
2009-01-01T22:06:09Z
405,564
18
2009-01-01T22:17:30Z
[ "python", "data-structures", "recursion", "cyclic-reference" ]
I was just reading through ["Learning Python" by Mark Lutz and came across this code sample](http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false): ``` >>> L = ['grail'] >>> L.append(L) >>> L ['grail', [...]] ``` It was identified as a cyclic data structure. ...
Lots of things. Circular buffer, for example: you have some collection of data with a front and a back, but an arbitrary number of nodes, and the "next" item from the last should take you back to the first. Graph structures are often cyclic; acyclicity is a special case. Consider, for example, a graph containing all t...
Function and class documentation best practices for Python
405,582
68
2009-01-01T22:30:39Z
405,710
45
2009-01-01T23:54:52Z
[ "python", "documentation", "coding-style" ]
I am looking for best practices for function/class/module documentation, i.e. comments in the code itself. Ideally I would like a comment template which is both human readable and consumable by Python documentation utilities. I have read the [Python documentation on docstrings](http://docs.python.org/tutorial/controlf...
You should [use reStructuredText](http://www.python.org/dev/peps/pep-0287/) and check out the [Sphinx markup constructs](http://sphinx.pocoo.org/markup/index.html). All the cool kids are doing it. You should [follow docstring conventions](http://www.python.org/dev/peps/pep-0257/). i.e. > It prescribes the function or...
Function and class documentation best practices for Python
405,582
68
2009-01-01T22:30:39Z
406,346
8
2009-01-02T09:05:02Z
[ "python", "documentation", "coding-style" ]
I am looking for best practices for function/class/module documentation, i.e. comments in the code itself. Ideally I would like a comment template which is both human readable and consumable by Python documentation utilities. I have read the [Python documentation on docstrings](http://docs.python.org/tutorial/controlf...
As Emji said, Django is a good project to follow for clear, consistent style guides. For example, their [Contribute to Django style guide](http://docs.djangoproject.com/en/dev/internals/contributing/?from=olddocs#coding-style) even goes as far as describing how they'd like to see documentation. Specifically they menti...
Accepting File Argument in Python (from Send To context menu)
405,612
3
2009-01-01T22:50:42Z
405,629
7
2009-01-01T22:57:47Z
[ "python", "urllib2", "contextmenu", "sendto" ]
I'm going to start of by noting that I have next to no python experience. ![alt text](http://www.aquate.us/u/9986423875612301299.jpg) As you may know, by simply dropping a shortcut in the Send To folder on your Windows PC, you can allow a program to take a file as an argument. How would I write a python program that...
1. Find out what the dragged file was: <http://docs.python.org/library/sys.html#sys.argv> 2. Open it: <http://docs.python.org/library/functions.html#open> 3. Read it in: <http://docs.python.org/library/stdtypes.html#file.read> 4. Post it: <http://docs.python.org/library/urllib2.html#urllib2.urlopen>
Passing arguments with wildcards to a Python script
405,652
12
2009-01-01T23:08:01Z
405,662
20
2009-01-01T23:15:46Z
[ "python", "windows", "command-line", "arguments" ]
I want to do something like this: ``` c:\data\> python myscript.py *.csv ``` and pass all of the .csv files in the directory to my python script (such that `sys.argv` contains `["file1.csv", "file2.csv"]`, etc.) But `sys.argv` just receives `["*.csv"]` indicating that the wildcard was not expanded, so this doesn't w...
You can use the glob module, that way you won't depend on the behavior of a particular shell (well, you still depend on the shell not expanding the arguments, but at least you can get this to happen in Unix by escaping the wildcards :-) ). ``` from glob import glob filelist = glob('*.csv') #You can pass the sys.argv a...
Passing arguments with wildcards to a Python script
405,652
12
2009-01-01T23:08:01Z
405,667
11
2009-01-01T23:19:50Z
[ "python", "windows", "command-line", "arguments" ]
I want to do something like this: ``` c:\data\> python myscript.py *.csv ``` and pass all of the .csv files in the directory to my python script (such that `sys.argv` contains `["file1.csv", "file2.csv"]`, etc.) But `sys.argv` just receives `["*.csv"]` indicating that the wildcard was not expanded, so this doesn't w...
In Unix, the shell expands wildcards, so programs get the expanded list of filenames. Windows doesn't do this: the shell passes the wildcards directly to the program, which has to expand them itself. Vinko is right: the glob module does the job: ``` import glob, sys for arg in glob.glob(sys.argv[1]): print "Arg:...
Floating Point Limitations
406,361
4
2009-01-02T09:17:26Z
406,367
18
2009-01-02T09:22:15Z
[ "python", "floating-point", "precision", "floating-accuracy" ]
My code: ``` a = '2.3' ``` I wanted to display `a` as a floating point value. Since `a` is a string, I tried: ``` float(a) ``` The result I got was : ``` 2.2999999999999998 ``` I want a solution for this problem. Please, kindly help me. I was following [this tutorial](http://docs.python.org/tutorial/floatingpoi...
I think it reflects more on your understanding of floating point types than on Python. See [my article about floating point numbers](http://csharpindepth.com/Articles/General/FloatingPoint.aspx) (.NET-based, but still relevant) for the reasons behind this "inaccuracy". If you need to keep the exact decimal representati...
Why does Ruby have Rails while Python has no central framework?
406,907
8
2009-01-02T14:26:57Z
406,925
7
2009-01-02T14:33:24Z
[ "python", "ruby-on-rails", "ruby", "frameworks", "history" ]
This is a(n) historical question, not a comparison-between-languages question: [This article from 2005](http://tomayko.com/writings/no-rails-for-python) talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. **Why, historically speaking, did this happen for Ruby but ...
I don't think it's right to characterise Rails as 'the' 'single' 'central' Ruby framework. Other frameworks for Ruby include Merb, Camping and Ramaze. ... which sort of invalidates the question.
Why does Ruby have Rails while Python has no central framework?
406,907
8
2009-01-02T14:26:57Z
407,003
35
2009-01-02T15:03:40Z
[ "python", "ruby-on-rails", "ruby", "frameworks", "history" ]
This is a(n) historical question, not a comparison-between-languages question: [This article from 2005](http://tomayko.com/writings/no-rails-for-python) talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. **Why, historically speaking, did this happen for Ruby but ...
As I see it, Rails put Ruby on the map. The simple fact is that before Rails, Ruby was a minor esoteric language, with very little adoption. Ruby owes its success to Rails. As such, Rails has a central place in the Ruby ecosystem. As slim points out, there are other web frameworks, but it's going to be very difficult t...
Why does Ruby have Rails while Python has no central framework?
406,907
8
2009-01-02T14:26:57Z
408,146
7
2009-01-02T22:08:20Z
[ "python", "ruby-on-rails", "ruby", "frameworks", "history" ]
This is a(n) historical question, not a comparison-between-languages question: [This article from 2005](http://tomayko.com/writings/no-rails-for-python) talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. **Why, historically speaking, did this happen for Ruby but ...
The real technical answer is that there are three major approaches to web-development in Python: one is CGI-based, where the application is built just like an old one-off Perl application to run through CGI or FastCGI, e.g. [Trac](http://trac.edgewall.org/); then there is [Zope](http://zope.org/), which is a bizarro ov...
How to intercept special (alt / ctrl) key press?
406,933
8
2009-01-02T14:34:45Z
407,022
10
2009-01-02T15:09:56Z
[ "python", "curses" ]
How can I catch key combinations like `ALT`+`K` or `CTRL`+`ALT`+`H` in python `curses`?
A terminal converts the control key in combination with a letter key to a normal ASCII code. This can be read from the [getch](http://www.opengroup.org/onlinepubs/007908799/xcurses/wgetch.html)() function like any other key press. ``` CTRL-A: getch() returns 1 CTRL-B: getch() returns 2 ... CTRL-Z: getch() returns 26 `...
Python: Set Bits Count (popcount)
407,587
13
2009-01-02T18:09:07Z
407,674
8
2009-01-02T18:42:26Z
[ "python", "bit-manipulation" ]
Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL\_RAW.BIT\_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above. During a small experiment, i wanted to see what is the hex and the integer value produced and wrot...
what you're looking for is called the [Hamming Weight](http://en.wikipedia.org/wiki/Hamming_weight). in python 2.6/3.0 it can be found rather easily with: ``` bits = sum( b == '1' for b in bin(x)[2:] ) ```
Python: Set Bits Count (popcount)
407,587
13
2009-01-02T18:09:07Z
407,758
29
2009-01-02T19:12:55Z
[ "python", "bit-manipulation" ]
Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL\_RAW.BIT\_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above. During a small experiment, i wanted to see what is the hex and the integer value produced and wrot...
Python 2.6 or 3.0: ``` def bitsoncount(x): return bin(x).count('1') ``` Example: ``` >>> x = 123 >>> bin(x) '0b1111011' >>> bitsoncount(x) 6 ``` Or [Matt Howells's answer](http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer#109025) in Python: ``` def b...
A generic priority queue for Python
407,734
33
2009-01-02T19:05:54Z
407,755
31
2009-01-02T19:11:31Z
[ "python", "queue" ]
I need to use a priority queue in my Python code. Looking around for something efficient, I came upon [heapq](http://docs.python.org/library/heapq.html). It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison...
Um, [Queue.PriorityQueue](http://docs.python.org/library/queue.html#Queue.PriorityQueue) ? Recall that Python isn't strongly typed, so you can save anything you like: just make a tuple of (priority,thing) and you're set.
A generic priority queue for Python
407,734
33
2009-01-02T19:05:54Z
407,759
7
2009-01-02T19:13:33Z
[ "python", "queue" ]
I need to use a priority queue in my Python code. Looking around for something efficient, I came upon [heapq](http://docs.python.org/library/heapq.html). It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison...
Did you look at the ["Show Source" link](http://docs.python.org/_sources/library/heapq.txt) on the heapq page? There's an example a little less than halfway down of using a heap with a list of (int, char) tuples as a priority queue.
A generic priority queue for Python
407,734
33
2009-01-02T19:05:54Z
407,922
16
2009-01-02T20:19:36Z
[ "python", "queue" ]
I need to use a priority queue in my Python code. Looking around for something efficient, I came upon [heapq](http://docs.python.org/library/heapq.html). It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison...
I ended up implementing a wrapper for `heapq`, adding a dict for maintaining the queue's elements unique. The result should be quite efficient for all operators: ``` class PriorityQueueSet(object): """ Combined priority queue and set data structure. Acts like a priority queue, except that its items are g...
How to produce a 303 Http Response in Django?
408,541
17
2009-01-03T03:20:07Z
408,549
23
2009-01-03T03:25:12Z
[ "python", "django", "http", "rest" ]
Last couple of days we were discussing at [another question](http://stackoverflow.com/questions/401191/how-to-return-random-items-restfully) the best to manage randomness in a RESTful way; today I went to play a little bit with some ideas in Django only to find that there is no easy standard way of returning a 303 resp...
You could just override HttpResponse, like the other Responses do: ``` class HttpResponseSeeOther(HttpResponseRedirect): status_code = 303 return HttpResponseSeeOther('/other-url/') ```
How to produce a 303 Http Response in Django?
408,541
17
2009-01-03T03:20:07Z
408,572
19
2009-01-03T03:54:35Z
[ "python", "django", "http", "rest" ]
Last couple of days we were discussing at [another question](http://stackoverflow.com/questions/401191/how-to-return-random-items-restfully) the best to manage randomness in a RESTful way; today I went to play a little bit with some ideas in Django only to find that there is no easy standard way of returning a 303 resp...
The generic HttpResponse object lets you specify any status code you want: ``` response = HttpResponse(content="", status=303) response["Location"] = "http://example.com/redirect/here/" ``` If you need something re-usable then Gerald's answer is definitely valid; simply create your own HttpResponseSeeOther class. Dja...
Python human readable object serialization
408,866
15
2009-01-03T10:30:40Z
408,889
11
2009-01-03T10:52:05Z
[ "python", "json", "yaml", "serialization", "pickle" ]
i need to store Python structures made of lists / dictionaries, tuples into a human readable format. The idea is like using something similar to [pickle](http://docs.python.org/library/pickle.html), but pickle is not human-friendly. Other options that come to my mind are [YAML](http://en.wikipedia.org/wiki/Yaml) (throu...
For simple cases pprint() and eval() come to mind. Using your example: ``` >>> d = {'age': 27, ... 'name': 'Joe', ... 'numbers': [1, ... 2, ... 3, ... 4, ... 5], ... 'subdict': { ... 'first': 1, ... 'second': 2, ... 'thi...
Python human readable object serialization
408,866
15
2009-01-03T10:30:40Z
408,912
12
2009-01-03T11:04:55Z
[ "python", "json", "yaml", "serialization", "pickle" ]
i need to store Python structures made of lists / dictionaries, tuples into a human readable format. The idea is like using something similar to [pickle](http://docs.python.org/library/pickle.html), but pickle is not human-friendly. Other options that come to my mind are [YAML](http://en.wikipedia.org/wiki/Yaml) (throu...
If its **just** Python list, dictionary and tuple object. - **JSON** is the way to go. Its human readable, very easy to handle and language independent too. Caution: Tuples will be converted to lists in simplejson. ``` In [109]: simplejson.loads(simplejson.dumps({'d':(12,3,4,4,5)})) Out[109]: {u'd': [12, 3, 4, 4, 5]}...
Sorting and Grouping Nested Lists in Python
409,370
23
2009-01-03T17:05:30Z
409,423
37
2009-01-03T17:29:07Z
[ "python" ]
I have the following data structure (a list of lists) ``` [ ['4', '21', '1', '14', '2008-10-24 15:42:58'], ['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['5', '21', '3', '19', '2008-10-24 15:45:45'], ['6', '21', '1', '1somename', '2008-10-24 15:45:49'], ['7', '22', '3', '2somename', '2008-10-24 15:45:...
For the first question, the first thing you should do is sort the list by the second field: ``` x = [ ['4', '21', '1', '14', '2008-10-24 15:42:58'], ['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['5', '21', '3', '19', '2008-10-24 15:45:45'], ['6', '21', '1', '1somename', '2008-10-24 15:45:49'], ['7', ...
Loop function parameters for sanity check
409,449
3
2009-01-03T17:41:09Z
409,564
7
2009-01-03T18:43:01Z
[ "python", "function", "parameters", "arguments", "sanitization" ]
I have a Python function in which I am doing some sanitisation of the input parameters: ``` def func(param1, param2, param3): param1 = param1 or '' param2 = param2 or '' param3 = param3 or '' ``` This caters for the arguments being passed as *None* rather than empty strings. Is there an easier/more concis...
This looks like a good job for a decorator. How about this: ``` def sanitized(func): def sfunc(*args, **kwds): return func(*[arg or '' for arg in args], **dict((k, v or '') for k,v in kwds.iteritems())) sfunc.func_name = func.func_name sfunc.func_doc = func.func_doc return s...
Avoid exceptions?
409,529
8
2009-01-03T18:19:50Z
409,704
7
2009-01-03T19:52:37Z
[ "python", "django", "exception" ]
This particular example relates to Django in Python, but should apply to any language supporting exceptions: ``` try: object = ModelClass.objects.get(search=value) except DoesNotExist: pass if object: # do stuff ``` The Django model class provides a simple method *get* which allows me to search for *one ...
There's a big schism in programming languages around the use of exceptions. * The majority view is that **exceptions should be exceptional**. In most languages with exceptions, transfer of control by exception is considerably more expensive than by procedure return, for example. * There is a strong minority view that ...
Avoid exceptions?
409,529
8
2009-01-03T18:19:50Z
410,115
8
2009-01-03T23:57:18Z
[ "python", "django", "exception" ]
This particular example relates to Django in Python, but should apply to any language supporting exceptions: ``` try: object = ModelClass.objects.get(search=value) except DoesNotExist: pass if object: # do stuff ``` The Django model class provides a simple method *get* which allows me to search for *one ...
Believe it or not, this actually is an issue that is a bit different in each language. In Python, exceptions are regularly thrown for events that aren't exceptional by the language itself. Thus I think that the "you should only throw exceptions under exceptional circumstances" rule doesn't quite apply. I think the resu...
Python: Alter elements of a list
409,732
15
2009-01-03T20:07:28Z
409,744
13
2009-01-03T20:13:14Z
[ "python", "coding-style" ]
I have a list of booleans where occasionally I reset them all to false. After first writing the reset as: ``` for b in bool_list: b = False ``` I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value....
If you only have one reference to the list, the following may be easier: ``` bool_list = [False] * len(bool_list) ``` This creates a new list populated with `False` elements. See my answer to [Python dictionary clear](http://stackoverflow.com/questions/369898/python-dictionary-clear#369925) for a similar example.
Python: Alter elements of a list
409,732
15
2009-01-03T20:07:28Z
409,764
13
2009-01-03T20:30:42Z
[ "python", "coding-style" ]
I have a list of booleans where occasionally I reset them all to false. After first writing the reset as: ``` for b in bool_list: b = False ``` I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value....
Here's another version: ``` bool_list = [False for item in bool_list] ```
Python: Alter elements of a list
409,732
15
2009-01-03T20:07:28Z
410,067
11
2009-01-03T23:11:59Z
[ "python", "coding-style" ]
I have a list of booleans where occasionally I reset them all to false. After first writing the reset as: ``` for b in bool_list: b = False ``` I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value....
``` bool_list[:] = [False] * len(bool_list) ``` or ``` bool_list[:] = [False for item in bool_list] ```
Python: Alter elements of a list
409,732
15
2009-01-03T20:07:28Z
410,213
12
2009-01-04T01:09:25Z
[ "python", "coding-style" ]
I have a list of booleans where occasionally I reset them all to false. After first writing the reset as: ``` for b in bool_list: b = False ``` I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value....
**Summary** Performance-wise, numpy or a list multiplication are clear winners, as they are 10-20x faster than other approaches. I did some performance testing on the various options proposed. I used Python 2.5.2, on Linux (Ubuntu 8.10), with a 1.5 Ghz Pentium M. **Original:** ``` python timeit.py -s 'bool_list = [T...
socket.shutdown vs socket.close
409,783
87
2009-01-03T20:37:55Z
409,843
21
2009-01-03T21:10:08Z
[ "python", "sockets", "asynchronous" ]
I recently saw a bit of code that looked like this (with sock being a socket object of course): ``` sock.shutdown(socket.SHUT_RDWR) sock.close() ``` What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.
Here's one [explanation](http://publib.boulder.ibm.com/infocenter/systems/index.jsp?topic=/com.ibm.aix.progcomm/doc/progcomc/skt_shutdn.htm): > Once a socket is no longer required, > the calling program can discard the > socket by applying a close subroutine > to the socket descriptor. If a > reliable delivery socket ...
socket.shutdown vs socket.close
409,783
87
2009-01-03T20:37:55Z
410,231
16
2009-01-04T01:28:29Z
[ "python", "sockets", "asynchronous" ]
I recently saw a bit of code that looked like this (with sock being a socket object of course): ``` sock.shutdown(socket.SHUT_RDWR) sock.close() ``` What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.
Explanation of shutdown and close: [Graceful shutdown (msdn)](http://msdn.microsoft.com/en-us/library/ms738547(VS.85).aspx) Shutdown (in your case) indicates to the other end of the connection there is no further intention to read from or write to the socket. Then close frees up any memory associated with the socket. ...
socket.shutdown vs socket.close
409,783
87
2009-01-03T20:37:55Z
598,759
159
2009-02-28T21:58:05Z
[ "python", "sockets", "asynchronous" ]
I recently saw a bit of code that looked like this (with sock being a socket object of course): ``` sock.shutdown(socket.SHUT_RDWR) sock.close() ``` What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.
Calling `close` and `shutdown` have two different effects on the underlying socket. The first thing to point out is that the socket is a resource in the underlying OS and **multiple processes can have a handle for the same underlying socket.** When you call `close` it decrements the handle count by one and if the han...
How do you embed album art into an MP3 using Python?
409,949
21
2009-01-03T21:59:30Z
1,002,814
10
2009-06-16T17:13:44Z
[ "python", "mp3", "metadata", "id3", "albumart" ]
I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.
I've used the [eyeD3](http://eyed3.nicfit.net/) module to do this exact thing. ``` def update_id3(mp3_file_name, artwork_file_name, artist, item_title): #edit the ID3 tag to add the title, artist, artwork, date, and genre tag = eyeD3.Tag() tag.link(mp3_file_name) tag.setVersion([2,3,0]) tag.add...
How do you embed album art into an MP3 using Python?
409,949
21
2009-01-03T21:59:30Z
1,937,425
28
2009-12-20T23:02:50Z
[ "python", "mp3", "metadata", "id3", "albumart" ]
I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.
Here is how to add example.png as album cover into example.mp3 with mutagen: ``` from mutagen.mp3 import MP3 from mutagen.id3 import ID3, APIC, error audio = MP3('example.mp3', ID3=ID3) # add ID3 tag if it doesn't exist try: audio.add_tags() except error: pass audio.tags.add( APIC( encoding=3, #...
For Python programmers, is there anything equivalent to Perl's CPAN?
410,163
32
2009-01-04T00:30:37Z
410,170
32
2009-01-04T00:34:17Z
[ "python", "perl" ]
I'm learning Python now because of the Django framework. I have been a Perl programmer for a number of years and I'm so used to Perl's tools. One of the things that I really miss is Perl's CPAN and its tools. Is there anything equivalent in Python? I would like to be able to search, install and maintain Python modules ...
sammy, have a look at [pip](http://pip.openplans.org/), which will let you do "pip install foo", and will download and install its dependencies (as long as they're on [PyPI](http://pypi.python.org/)). There's also [EasyInstall](http://peak.telecommunity.com/DevCenter/EasyInstall), but pip is intended to replace that.
For Python programmers, is there anything equivalent to Perl's CPAN?
410,163
32
2009-01-04T00:30:37Z
412,211
10
2009-01-05T03:32:27Z
[ "python", "perl" ]
I'm learning Python now because of the Django framework. I have been a Perl programmer for a number of years and I'm so used to Perl's tools. One of the things that I really miss is Perl's CPAN and its tools. Is there anything equivalent in Python? I would like to be able to search, install and maintain Python modules ...
It might be useful to note that pip and easy\_install both use the [Python Package Index (PyPI)](http://pypi.python.org/pypi), sometimes called the "Cheeseshop", to search for packages. Easy\_install is currently the most universally supported, as it works with both setuptools and distutils style packaging, completely....
Natural/Relative days in Python
410,221
31
2009-01-04T01:20:55Z
410,335
7
2009-01-04T03:02:03Z
[ "python", "datetime", "human-readable", "datetime-parsing", "humanize" ]
I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc. Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited th...
Or you could easily adapt [timesince.py](http://code.djangoproject.com/browser/django/trunk/django/utils/timesince.py) from Django which only has 2 other dependencies to itself: one for translation (which you might not need) and one for timezones (which can be easily adapted). By the way, [Django has a BSD license](ht...
Natural/Relative days in Python
410,221
31
2009-01-04T01:20:55Z
410,482
16
2009-01-04T04:52:36Z
[ "python", "datetime", "human-readable", "datetime-parsing", "humanize" ]
I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc. Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited th...
While not useful to you at this very moment, it may be so for future searchers: The babel module, which deals with all sorts of locale stuff, has a function for doing more or less what you want. Currently it's only in their trunk though, not in the latest public release (version 0.9.4). Once the functionality lands in ...
Natural/Relative days in Python
410,221
31
2009-01-04T01:20:55Z
5,164,027
29
2011-03-02T06:09:12Z
[ "python", "datetime", "human-readable", "datetime-parsing", "humanize" ]
I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc. Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited th...
Twitter dates in specific are interesting because they are relative only for the first day. After 24 hours they just show the month and day. After a year they start showing the last two digits of the year. Here's a sample function that does something more akin to Twitter relative dates, though it always shows the year ...
what's the 5 character alphanumeric id in reddit URL?
410,485
12
2009-01-04T05:00:52Z
410,504
24
2009-01-04T05:21:43Z
[ "python", "url", "slug", "reddit" ]
Whats the `7n5lu` in the reddit URL `http://www.reddit.com/r/reddit.com/comments/7n5lu/man_can_fly_if_you_watch_one_video_in_2` how is it generated? update: @Gerald, Thanks for the code. I initially thought this is some obfuscation of the id. But, it is just doing the conversion from integer to a more compact represe...
The reddit source code [is available](https://github.com/reddit/reddit)! Here is what I found for generating that string: ``` def to_base(q, alphabet): if q < 0: raise ValueError, "must supply a positive integer" l = len(alphabet) converted = [] while q != 0: q, r = divmod(q, l) convert...
How do I parse XML from a Google app engine app?
410,954
14
2009-01-04T13:05:41Z
410,971
8
2009-01-04T13:27:43Z
[ "python", "xml", "google-app-engine", "parsing" ]
How do I parse XML from a Google app engine app? Any examples?
Take a look at [existing answers on XML and Python](http://stackoverflow.com/search?q=iterparse). Something like this could work: ``` from cStringIO import StringIO from xml.etree import cElementTree as etree xml = "<a>aaa<b>bbb</b></a>" for event, elem in etree.iterparse(StringIO(xml)): print elem.text ```...
How do I parse XML from a Google app engine app?
410,954
14
2009-01-04T13:05:41Z
711,167
20
2009-04-02T19:09:49Z
[ "python", "xml", "google-app-engine", "parsing" ]
How do I parse XML from a Google app engine app? Any examples?
Since the question was asked, Google has whitelisted pyexpat, which includes minidom, so you can use the following code without having to upload any libraries: ``` from xml.dom import minidom dom = minidom.parseString('<eg>example text</eg>') ``` More information: <http://docs.python.org/library/xml.dom.minidom.html...
Variable number of inputs with Django forms possible?
411,761
17
2009-01-04T22:00:33Z
411,852
7
2009-01-04T22:57:03Z
[ "python", "django", "django-forms" ]
Is it possible to have a variable number of fields using django forms? The specific application is this: A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures wil...
If you run ``` python manage.py shell ``` and type: ``` from app.forms import PictureForm p = PictureForm() p.fields type(p.fields) ``` you'll see that p.fields is a SortedDict. you just have to insert a new field. Something like ``` p.fields.insert(len(p.fields)-2, 'fieldname', Field()) ``` In this case it would...
Variable number of inputs with Django forms possible?
411,761
17
2009-01-04T22:00:33Z
411,862
7
2009-01-04T23:00:48Z
[ "python", "django", "django-forms" ]
Is it possible to have a variable number of fields using django forms? The specific application is this: A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures wil...
Use either multiple forms (django.forms.Form not the tag) ``` class Foo(forms.Form): field = forms.Charfield() forms = [Foo(prefix=i) for i in xrange(x)] ``` or add multiple fields to the form dynamically using self.fields. ``` class Bar(forms.Form): def __init__(self, fields, *args, **kwargs): supe...
Variable number of inputs with Django forms possible?
411,761
17
2009-01-04T22:00:33Z
412,149
13
2009-01-05T02:35:12Z
[ "python", "django", "django-forms" ]
Is it possible to have a variable number of fields using django forms? The specific application is this: A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures wil...
Yes, it's possible to create forms dynamically in Django. You can even mix and match dynamic fields with normal fields. ``` class EligibilityForm(forms.Form): def __init__(self, *args, **kwargs): super(EligibilityForm, self).__init__(*args, **kwargs) # dynamic fields here ... self.fields['p...
How do I retrieve a Django model class dynamically?
411,810
15
2009-01-04T22:32:50Z
411,880
32
2009-01-04T23:11:28Z
[ "python", "django", "django-models", "django-queryset" ]
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e....
I think you're looking for this: ``` from django.db.models.loading import get_model model = get_model('app_name', 'model_name') ``` There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get...
How do I retrieve a Django model class dynamically?
411,810
15
2009-01-04T22:32:50Z
28,380,435
11
2015-02-07T09:19:49Z
[ "python", "django", "django-models", "django-queryset" ]
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e....
For Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model. ``` from django.apps import apps My...
Django file upload failing occasionally
411,902
8
2009-01-04T23:28:35Z
416,189
8
2009-01-06T11:33:53Z
[ "python", "django", "apache" ]
I am trying to port my first Django 1.0.2 application to run on OSX/Leopard with Apache + mod\_python 3.3.1 + python 2.6.1 (all running in 64-bit mode) and I am experiencing an occasional error when uploading a file that was not present when testing with the Django development server. The code for the upload is simila...
Using mod\_wsgi made the problem go away for Firefox. Limiting my research to an interaction problem between Apache and Safari, I stumbled upon this bug report for Apache <https://bugs.webkit.org/show_bug.cgi?id=5760> that describes something very similar to what is happening and it is apparently still open. Reading t...
How to (simply) connect Python to my web site?
412,368
3
2009-01-05T05:57:25Z
412,371
11
2009-01-05T06:00:41Z
[ "python", "website" ]
I've been playing with Python for a while and wrote a little program to make a database to keep track of some info (its really basic, and hand written). I want to add the ability to create a website from the data that I will then pass to my special little place on the internet. What should I use to build up the website...
I would generate a page or two of HTML using a template engine ([Jinja](http://jinja.pocoo.org/2/) is my personal choice) and just stick them in your `public_html` directory or wherever the webserver's root is.
Algorithm to keep a list of percentages to add up to 100%
412,943
4
2009-01-05T12:18:09Z
412,979
9
2009-01-05T12:33:25Z
[ "python", "algorithm" ]
(code examples are python) Lets assume we have a list of percentages that add up to 100: ``` mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] ``` Some values of mylist may be changed, others must stay fixed. Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed and the last three (35.0, 21.0, 23.0) may be changed. ...
How's this? ``` def adjustAppend( v, n ): weight= -n/sum(v) return [ i+i*weight for i in v ] + [n] ``` Given a list of numbers *v*, append a new number, *n*. Weight the existing number to keep the sum the same. ``` sum(v) == sum( v + [n] ) ``` Each element of *v*, *i*, must be reduced by some function of *...
How to implement property() with dynamic name (in python)
412,951
9
2009-01-05T12:19:45Z
412,997
10
2009-01-05T12:42:31Z
[ "python", "oop", "parameters", "properties" ]
I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge pa...
Look at built-in functions `getattr` and `setattr`. You'll probably be a lot happier.
How to implement property() with dynamic name (in python)
412,951
9
2009-01-05T12:19:45Z
439,708
7
2009-01-13T16:33:49Z
[ "python", "oop", "parameters", "properties" ]
I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge pa...
Using the same get/set functions for both classes forces you into an ugly hack with the argument list. Very sketchy, this is how I would do it: In class SingleParameter, define get and set as usual: ``` def get(self): return self._s def set(self, value): self._s = value ``` In class Collection, you cannot know t...
Is there a Python library than can simulate network traffic from different addresses
414,025
16
2009-01-05T18:20:39Z
414,078
17
2009-01-05T18:44:27Z
[ "python", "networking" ]
Is there a python library out there than can allow me to send UDP packets to a machine (sending to localhost is ok) from different source addresses and ports? I remember that one existed, but can't find it anymore.
You can spoof an IP address using [Scapy](http://www.secdev.org/projects/scapy/) library. Here's an example from [Packet Wizardry: Ruling the Network with Python](http://web.archive.org/web/20120401161821/http://packetstorm.linuxsecurity.com/papers/general/blackmagic.txt): ``` #!/usr/bin/env python import sys from sc...
python "'NoneType' object has no attribute 'encode'"
414,230
5
2009-01-05T19:35:09Z
414,239
12
2009-01-05T19:39:27Z
[ "python", "urlencode" ]
I wrote this tiny Python snippet that scrapes a feed and prints it out. When I run the code, something in the feed triggers the error message you see here as my question. Here's the complete console output on error: ``` > Traceback (most recent call last): > File "/home/vijay/ffour/ffour5.py", > line 20, in <module>...
> ``` > > sys.stdout.write(entry["title"]).encode('utf-8') > ``` This is the culprit. You probably mean: ``` sys.stdout.write(entry["title"].encode('utf-8')) ``` (Notice the position of the last closing bracket.)
Django serialize to JSON
414,543
15
2009-01-05T21:10:09Z
414,696
10
2009-01-05T22:11:28Z
[ "python", "django", "json" ]
I have a Django model (schedule) with the class of entity, that is the parent of `Activity`, that is the parent of `Event`. ``` class Entity(models.Model): <...> class Activity(models.Model): <...> team_entity = models.ForeignKey(Entity) <...> class Event(models.Model): <...> activity = mo...
Before you do serialization, when retrieving your objects, to preserve the relationships use select\_related() to get children, grandchildren, etc see <http://docs.djangoproject.com/en/dev/ref/models/querysets/>
Django serialize to JSON
414,543
15
2009-01-05T21:10:09Z
918,010
7
2009-05-27T21:05:55Z
[ "python", "django", "json" ]
I have a Django model (schedule) with the class of entity, that is the parent of `Activity`, that is the parent of `Event`. ``` class Entity(models.Model): <...> class Activity(models.Model): <...> team_entity = models.ForeignKey(Entity) <...> class Event(models.Model): <...> activity = mo...
I now use django-piston. This does the trick.
Add class to Django label_tag() output
414,679
16
2009-01-05T22:05:15Z
415,770
8
2009-01-06T08:00:00Z
[ "python", "django", "forms", "newforms" ]
I need some way to add a class attribute to the output of the label\_tag() method for a forms field. I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like: ``` for field in form: print field.label_tag(attrs{'class':'Foo'}) ``` I will see the ...
A [custom template tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags) seems to be the solution. A custom filter would also do, although it can be less elegant. But you would need to fall back to custom form rendering in both cases. If this is a task of high importance; I'...
Add class to Django label_tag() output
414,679
16
2009-01-05T22:05:15Z
1,933,711
10
2009-12-19T18:16:02Z
[ "python", "django", "forms", "newforms" ]
I need some way to add a class attribute to the output of the label\_tag() method for a forms field. I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like: ``` for field in form: print field.label_tag(attrs{'class':'Foo'}) ``` I will see the ...
How about adding the CSS class to the form field in the forms.py, like: ``` class MyForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'foo'})) ``` then I just do the following in the template: ``` <label for="id_{{form.title.name}}" class="bar"> {{ form.title }} </label> ``` O...
Add class to Django label_tag() output
414,679
16
2009-01-05T22:05:15Z
11,584,458
7
2012-07-20T17:49:31Z
[ "python", "django", "forms", "newforms" ]
I need some way to add a class attribute to the output of the label\_tag() method for a forms field. I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like: ``` for field in form: print field.label_tag(attrs{'class':'Foo'}) ``` I will see the ...
**Technique 1** I take issue with another answer's assertion that a filter would be "less elegant." As you can see, it's very elegant indeed. ``` @register.filter(is_safe=True) def label_with_classes(value, arg): return value.label_tag(attrs={'class': arg}) ``` Using this in a template is just as elegant: ``` ...
SQLAlchemy DateTime timezone
414,952
24
2009-01-05T23:46:02Z
462,028
14
2009-01-20T16:24:22Z
[ "python", "datetime", "timezone", "sqlalchemy" ]
SQLAlchemy's `DateTime` type allows for a `timezone=True` argument to save a non-naive datetime object to the datbase, and to return it as such. Is there any way to modify the timezone of the `tzinfo` that SQLAlchemy passes in so it could be, for instance, UTC? I realize that I could just use `default=datetime.datetime...
<http://www.postgresql.org/docs/8.3/interactive/datatype-datetime.html#DATATYPE-TIMEZONES> > All timezone-aware dates and times are stored internally in UTC. They are converted to local time in the zone specified by the timezone configuration parameter before being displayed to the client. The only way to store it wi...
Why does gethostbyaddr(gethostname()) return my IPv6 IP?
415,407
3
2009-01-06T04:01:41Z
415,417
11
2009-01-06T04:07:16Z
[ "python", "sockets", "ip-address", "ipv6", "ipv4" ]
I'm working on making a simple server application with python, and I'm trying to get the IP to bind the listening socket to. An example I looked at uses this: ``` HOST = gethostbyaddr(gethostname()) ``` With a little more processing after this, it should give me just the host IP as a string. This should return the IP...
Getting your IP address is harder than you might think. Check [this answer](http://stackoverflow.com/questions/270745/how-do-i-determine-all-of-my-ip-addresses-when-i-have-multiple-nics#274644) I gave for the one reliable way I've found. Here's what the answer says in case you don't like clicking on things: Use the ...
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
415,519
1,151
2009-01-06T04:57:05Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
``` >>> import datetime >>> datetime.datetime.now() datetime(2009, 1, 6, 15, 8, 24, 78915) ``` And just the time: ``` >>> datetime.datetime.time(datetime.datetime.now()) datetime.time(15, 8, 24, 78915) ``` The same but slightly more compact: ``` >>> datetime.datetime.now().time() ``` See the [**documentation**](ht...
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
415,525
475
2009-01-06T04:59:52Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
You can use [`time.strftime()`](http://docs.python.org/3.3/library/time.html?highlight=time.strftime#time.strftime): ``` >>> from time import gmtime, strftime >>> strftime("%Y-%m-%d %H:%M:%S", gmtime()) '2009-01-05 22:14:39' ```
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
415,527
66
2009-01-06T05:02:43Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
``` >>> from time import gmtime, strftime >>> strftime("%a, %d %b %Y %X +0000", gmtime()) 'Tue, 06 Jan 2009 04:54:56 +0000' ``` That outputs the current GMT in the specified format. There is also a localtime() method. This [page](http://docs.python.org/library/time.html#module-time) has more details.
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
416,605
74
2009-01-06T13:55:23Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
Do ``` from time import time t = time() ``` * `t` - float number, good for time interval measurement. There is some difference for Unix and Windows platforms.
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
4,538,034
26
2010-12-27T10:24:12Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
If you need current time as a `time` object: ``` >>> import datetime >>> now = datetime.datetime.now() >>> datetime.time(now.hour, now.minute, now.second) datetime.time(11, 23, 44) ```