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
os.path.basename works with URLs, why?
1,112,545
6
2009-07-11T00:16:17Z
1,112,701
12
2009-07-11T01:45:00Z
[ "python", "url", "path" ]
``` >>> os.path.basename('http://example.com/file.txt') 'file.txt' ``` .. and I thought `os.path.*` work only on local paths and not URLs? Note that the above example was run on Windows too .. with similar result.
In practice many functions of `os.path` are just string manipulation functions (which just *happen* to be especially handy for path manipulation) -- and since that's innocuous and occasionally handy, while formally speaking "incorrect", I doubt this will change anytime soon -- for more details, use the following simple...
Import python package from local directory into interpreter
1,112,618
36
2009-07-11T00:57:52Z
1,112,654
9
2009-07-11T01:23:31Z
[ "python" ]
I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in `sys.path.insert(0,'.')`. Is there a better way? Also, ``` from . import mypackage ``` fails with this error: ``` ValueError: Attempted rela...
See the documentation for sys.path: <http://docs.python.org/library/sys.html#sys.path> To quote: > If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the curre...
Import python package from local directory into interpreter
1,112,618
36
2009-07-11T00:57:52Z
1,112,661
20
2009-07-11T01:24:47Z
[ "python" ]
I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in `sys.path.insert(0,'.')`. Is there a better way? Also, ``` from . import mypackage ``` fails with this error: ``` ValueError: Attempted rela...
You can use relative imports only from in a module that was in turn imported as part of a package -- your script or interactive interpreter wasn't, so of course `from . import` (which means "import from the same package I got imported from") doesn't work. `import mypackage` will be fine once you ensure the parent direc...
Safety of Python 'eval' For List Deserialization
1,112,665
6
2009-07-11T01:25:19Z
1,112,684
18
2009-07-11T01:33:02Z
[ "python", "google-app-engine", "eval" ]
Are there any security exploits that could occur in this scenario: ``` eval(repr(unsanitized_user_input), {"__builtins__": None}, {"True":True, "False":False}) ``` where `unsanitized_user_input` is a str object. The string is user-generated and could be nasty. Assuming our web framework hasn't failed us, it's a real ...
It is indeed dangerous and the safest alternative is `ast.literal_eval` (see the [ast](http://docs.python.org/library/ast.html#module-ast) module in the standard library). You can of course build and alter an `ast` to provide e.g. evaluation of variables and the like before you eval the resulting AST (when it's down to...
Safety of Python 'eval' For List Deserialization
1,112,665
6
2009-07-11T01:25:19Z
1,112,699
8
2009-07-11T01:42:00Z
[ "python", "google-app-engine", "eval" ]
Are there any security exploits that could occur in this scenario: ``` eval(repr(unsanitized_user_input), {"__builtins__": None}, {"True":True, "False":False}) ``` where `unsanitized_user_input` is a str object. The string is user-generated and could be nasty. Assuming our web framework hasn't failed us, it's a real ...
If you can prove beyond doubt that `unsanitized_user_input` is a `str` instance from the Python built-ins with nothing tampered, then this is always safe. In fact, it'll be safe even without all those extra arguments since `eval(repr(astr)) = astr` for all such string objects. You put in a string, you get back out a st...
List of installed fonts OS X / C
1,113,040
4
2009-07-11T05:45:38Z
1,113,150
10
2009-07-11T07:23:45Z
[ "python", "c", "osx", "fonts" ]
I'm trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how?
Python with PyObjC installed (which is the case for Mac OS X 10.5+, so this code will work without having to install anything): ``` import Cocoa manager = Cocoa.NSFontManager.sharedFontManager() font_families = list(manager.availableFontFamilies()) ``` (based on [htw's answer](#1113072))
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,113,624
34
2009-07-11T12:32:48Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
Ruby has the concepts of *blocks*, which are essentially syntactic sugar around a section of code; they are a way to create closures and pass them to another method which may or may not use the block. A block can be invoked later on through a `yield` statement. For example, a simple definition of an `each` method on `...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,113,741
12
2009-07-11T13:41:54Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
What Ruby has over Python are its scripting language capabilities. Scripting language in this context meaning to be used for "glue code" in shell scripts and general text manipulation. These are mostly shared with Perl. First-class built-in regular expressions, $-Variables, useful command line options like Perl (-a, -...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,113,875
12
2009-07-11T14:52:21Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
I don't think "Ruby has X and Python doesn't, while Python has Y and Ruby doesn't" is the most useful way to look at it. They're quite similar languages, with many shared abilities. To a large degree, the difference is what the language makes elegant and readable. To use an example you brought up, both do theoreticall...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,113,880
19
2009-07-11T14:54:19Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
Python has a "we're all adults here" mentality. Thus, you'll find that Ruby has things like constants while Python doesn't (although Ruby's constants only raise a warning). The Python way of thinking is that if you want to make something constant, you should put the variable names in all caps and not change it. For ex...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,114,453
11
2009-07-11T19:20:50Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
Python has an explicit, builtin syntax for list-comprehenions and generators whereas in Ruby you would use map and code blocks. Compare ``` list = [ x*x for x in range(1, 10) ] ``` to ``` res = (1..10).map{ |x| x*x } ```
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,114,457
8
2009-07-11T19:26:02Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
I'm unsure of this, so I add it as an answer first. ## Python treats unbound methods as functions That means you can call a method either like `theobject.themethod()` or by `TheClass.themethod(anobject)`. Edit: Although the difference between methods and functions is small in Python, and non-existant in Python 3, it...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,114,487
9
2009-07-11T19:44:50Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
**Some others from:** <http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/> (If I have misintrepreted anything or any of these have changed on the Ruby side since that page was updated, someone feel free to edit...) Strings are mutable in Ruby, not in Python (where new strings ar...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,114,551
18
2009-07-11T20:20:17Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
You can import only specific functions from a module in Python. In Ruby, you import the whole list of methods. You could "unimport" them in Ruby, but it's not what it's all about. EDIT: let's take this Ruby module : ``` module Whatever def method1 end def method2 end end ``` if you include it in your code ...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,117,852
28
2009-07-13T05:42:03Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
## Python Example Functions are first-class variables in Python. You can declare a function, pass it around as an object, and overwrite it: ``` def func(): print "hello" def another_func(f): f() another_func(func) def func2(): print "goodbye" func = func2 ``` This is a fundamental feature of modern scripting langua...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,118,733
11
2009-07-13T10:35:00Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
"Variables that start with a capital letter becomes constants and can't be modified" Wrong. They can. You only get a warning if you do.
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,119,232
7
2009-07-13T12:46:18Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
I would like to mention Python descriptor API that allows one customize object-to-attribute "communication". It is also noteworthy that, in Python, one is free to implement an alternative protocol via overriding the default given through the default implementation of the `__getattribute__` method. Let me give more deta...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,139,857
12
2009-07-16T19:43:13Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
I'd like to suggest a variant of the original question, "What does Ruby have that Python doesn't, and vice versa?" which admits the disappointing answer, "Well, what can you do with either Ruby or Python that can't be done in Intercal?" Nothing on that level, because Python and Ruby are both part of the vast royal fami...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,302,166
16
2009-08-19T19:32:19Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
From Ruby's [website](http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/): Similarities As with Python, in Ruby,... > * There’s an interactive prompt (called irb). > * You can read docs on the command line (with the ri command instead of pydoc). > * There are no special line te...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
1,573,879
11
2009-10-15T17:26:53Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
Somewhat more on the infrastructure side: * Python has much better integration with C++ (via things like [Boost.Python](http://www.boost.org/doc/libs/1%5F40%5F0/libs/python/doc/index.html), [SIP](http://www.riverbankcomputing.com/software/sip/intro), and [Py++](http://www.language-binding.net/pyplusplus/pyplusplus.htm...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
3,073,441
11
2010-06-18T22:24:35Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
Shamelessly copy/pasted from: [Alex Martelli](http://stackoverflow.com/users/95810/alex-martelli) answer on *"[What's better about Ruby than Python](http://groups.google.com/group/comp.lang.python/msg/028422d707512283)"* thread from [comp.lang.python](http://groups.google.com/group/comp.lang.python "comp.lang.python") ...
What does Ruby have that Python doesn't, and vice versa?
1,113,611
264
2009-07-11T12:24:26Z
4,102,608
26
2010-11-05T00:24:23Z
[ "python", "ruby" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody cho...
Ultimately all answers are going to be subjective at some level, and the answers posted so far pretty much prove that you can't point to any one feature that isn't doable in the other language in an equally nice (if not similar) way, since both languages are very concise and expressive. I like Python's syntax. However...
Making a Makefile
1,114,667
2
2009-07-11T21:23:09Z
1,114,692
11
2009-07-11T21:34:01Z
[ "c++", "python", "c", "makefile" ]
How I can make a Makefile, because it's the best way when you distribute a program by source code. Remember that this is for a C++ program and I'm starting in the C development world. But is it possible to make a Makefile for my Python programs?
From your question it sounds like a tutorial or an overview of what Makefiles actually do might benefit you. A good places to start is the [GNU Make](http://www.gnu.org/software/make/manual/make.html) documentation. It includes the following overview "The make utility automatically determines which pieces of a large ...
Python converts string into tuple
1,114,813
3
2009-07-11T22:27:47Z
1,114,820
16
2009-07-11T22:30:10Z
[ "python" ]
Example: ``` regular_string = "%s %s" % ("foo", "bar") result = {} result["somekey"] = regular_string, print result["somekey"] # ('foo bar',) ``` Why `result["somekey"]` tuple now not string?
Because of comma at the end of the line.
Python converts string into tuple
1,114,813
3
2009-07-11T22:27:47Z
1,114,837
9
2009-07-11T22:39:06Z
[ "python" ]
Example: ``` regular_string = "%s %s" % ("foo", "bar") result = {} result["somekey"] = regular_string, print result["somekey"] # ('foo bar',) ``` Why `result["somekey"]` tuple now not string?
When you write ``` result["somekey"] = regular_string, ``` Python reads ``` result["somekey"] = (regular_string,) ``` `(x,)` is the syntax for a tuple with a single element. Parentheses are assumed. And you really end up putting a tuple, instead of a string there.
Sorting disk I/O errors in Python
1,115,203
2
2009-07-12T02:48:05Z
1,115,216
7
2009-07-12T03:01:12Z
[ "python", "exception" ]
How do I sort out (distinguish) an error derived from a "disk full condition" from "trying to write to a read-only file system"? I don't want to fill my HD to find out :) What I want is to know who to catch each exception, so my code can say something to the user when he is trying to write to a ReadOnly FS and another ...
Once you catch `IOError`, e.g. with an `except IOError, e:` clause in Python 2.\*, you can examine `e.errno` to find out exactly what kind of I/O error it was (unfortunately in a way that's not necessarily fully portable among different operating systems). See the [errno](http://docs.python.org/library/errno.html) mod...
Cost of len() function
1,115,313
106
2009-07-12T04:31:02Z
1,115,329
109
2009-07-12T04:40:31Z
[ "python", "algorithm", "collections", "complexity-theory" ]
What is the cost of [`len()`](https://docs.python.org/2/library/functions.html#len) function for Python built-ins? (list/tuple/string/dictionary)
It's **O(1)** (very fast) on every type you've mentioned, plus `set` and others such as `array.array`.
Cost of len() function
1,115,313
106
2009-07-12T04:31:02Z
1,115,349
97
2009-07-12T04:59:44Z
[ "python", "algorithm", "collections", "complexity-theory" ]
What is the cost of [`len()`](https://docs.python.org/2/library/functions.html#len) function for Python built-ins? (list/tuple/string/dictionary)
Calling len() on those data types is O(1) in [CPython](http://www.python.org), the most common implementation of the Python language. Here's a link to a table that provides the algorithmic complexity of many different functions in CPython: [TimeComplexity Python Wiki Page](http://wiki.python.org/moin/TimeComplexity)
Cost of len() function
1,115,313
106
2009-07-12T04:31:02Z
1,115,382
33
2009-07-12T05:34:28Z
[ "python", "algorithm", "collections", "complexity-theory" ]
What is the cost of [`len()`](https://docs.python.org/2/library/functions.html#len) function for Python built-ins? (list/tuple/string/dictionary)
The below measurements provide evidence that `len()` is O(1) for oft-used data structures. A note regarding `timeit`: When the `-s` flag is used and two strings are passed to `timeit` the first string is executed only once and is not timed. ### List: ``` $ python -m timeit -s "l = range(10);" "len(l)" 10000000 loops...
Cost of len() function
1,115,313
106
2009-07-12T04:31:02Z
1,115,401
19
2009-07-12T06:17:13Z
[ "python", "algorithm", "collections", "complexity-theory" ]
What is the cost of [`len()`](https://docs.python.org/2/library/functions.html#len) function for Python built-ins? (list/tuple/string/dictionary)
All those objects keep track of their own length. The time to extract the length is small (O(1) in big-O notation) and mostly consists of [rough description, written in Python terms, not C terms]: look up "len" in a dictionary and dispatch it to the built\_in len function which will look up the object's `__len__` metho...
Static methods and thread safety
1,115,420
2
2009-07-12T06:32:23Z
1,115,427
7
2009-07-12T06:40:47Z
[ "python", "django", "thread-safety" ]
In python with all this idea of "Everything is an object" where is thread-safety? I am developing django website with wsgi. Also it would work in linux, and as I know they use effective process management, so we could not think about thread-safety alot. I am not doubt in how module loads, and there functions are stati...
Functions in a module are equivalent to static methods in a class. The issue of thread safety arises when multiple threads may be modifying shared data, or even one thread may be modifying such data while others are reading it; it's best avoided by making data be owned by ONE module (accessed via Queue.Queue from other...
Should I use Unicode string by default?
1,116,449
17
2009-07-12T17:13:22Z
1,116,476
17
2009-07-12T17:31:49Z
[ "python", "unicode" ]
Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '\_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case whe...
From my practice -- use unicode. At beginning of one project we used usuall strings, however our project was growing, we were implementing new features and using new third-party libraries. In that mess with non-unicode/unicode string some functions started failing. We started spending time localizing this problems and...
Should I use Unicode string by default?
1,116,449
17
2009-07-12T17:13:22Z
1,116,546
13
2009-07-12T17:59:19Z
[ "python", "unicode" ]
Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '\_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case whe...
As you ask this question, I suppose you are using Python 2.x. Python 3.0 changed quite a lot in string representation, and all text now is unicode. I would go for unicode in any new project - in a way compatible with the switch to Python 3.0 (see [details](http://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-in...
Should I use Unicode string by default?
1,116,449
17
2009-07-12T17:13:22Z
1,116,660
13
2009-07-12T18:54:32Z
[ "python", "unicode" ]
Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '\_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case whe...
Yes, use unicode. Some hints: 1. When doing input output in any sort of binary format, decode directly after reading and encode directly before writing, so that you never need to mix strings and unicode. Because mixing that tends to lead to UnicodeEncodeDecodeErrors sooner or later. 2. [Forget about this one, my expl...
What's the point of this code pattern?
1,116,693
3
2009-07-12T19:21:21Z
1,116,705
8
2009-07-12T19:27:26Z
[ "python" ]
I was trying to create a python wrapper for an tk extension, so I looked at Tkinter.py to learn how to do it. While looking at that file, I found the following pattern appears a lot of times: an internal method (hinted by the leading "\_" in the method name) is defined, then a public method is defined just to be the i...
Sometimes, you may want to change a method's behavior. For example, I could do this (hypothetically within the Misc class): ``` def _another_register(self, func, subst=None, needcleanup=1): ... def change_register(self): self.register = self._another_register def restore_register(self): self.register = s...
Django Initialization
1,116,948
9
2009-07-12T21:19:42Z
1,117,100
9
2009-07-12T22:35:25Z
[ "python", "django" ]
I have a big array, that I would like to load into memory only once when django starts up and then treat it as a read only global variable. What is the best place to put the code for the initialization of that array? If I put it in settings.py it will be reinitialized every time the settings module is imported, correc...
settings.py is the right place for that. Settings.py is, like any other module, loaded once. There is still the problem of the fact that a module must be imported once for each process, so a respawning style of web server (like apache) will reload it once for each instance in question. For mod\_python this will be once...
Django Initialization
1,116,948
9
2009-07-12T21:19:42Z
1,117,692
14
2009-07-13T04:23:30Z
[ "python", "django" ]
I have a big array, that I would like to load into memory only once when django starts up and then treat it as a read only global variable. What is the best place to put the code for the initialization of that array? If I put it in settings.py it will be reinitialized every time the settings module is imported, correc...
settings.py is for Django settings; it's fine to put your own settings in there, but using it for arbitrary non-configuration data structures isn't good practice. Just put it in the module it logically belongs to, and it'll be run just once per instance. If you want to guarantee that the module is loaded on startup an...
lucene / python
1,116,967
5
2009-07-12T21:29:23Z
1,116,984
8
2009-07-12T21:33:35Z
[ "python", "lucene" ]
Can I use lucene directly from python, preferably without using a binary module? I am interested mainly in read access -- being able to perform queries from python over existing lucene indexes.
You can't use Lucene itself from CPython without using a binary module, no. You could use it directly from [Jython](http://jython.org/), or you could use a Python port of Lucene, eg. [Lupy](http://pypi.python.org/pypi/Lupy/0.2.1) (though Lupy is no longer under development). If you're prepared to relax your non-binar...
lucene / python
1,116,967
5
2009-07-12T21:29:23Z
1,116,989
7
2009-07-12T21:34:49Z
[ "python", "lucene" ]
Can I use lucene directly from python, preferably without using a binary module? I am interested mainly in read access -- being able to perform queries from python over existing lucene indexes.
[PyLucene](http://lucene.apache.org/pylucene/) is a Python wrapper around Lucene. Therefore, you have to install Lucene as well, and its installation may be a bit complex (especially on Windows!)
does python have conversion operators?
1,117,149
5
2009-07-12T22:59:00Z
1,117,163
10
2009-07-12T23:09:13Z
[ "python", "operators" ]
I don't think so, but I thought I'd ask just in case. For example, for use in a class that encapsulates an int: ``` i = IntContainer(3) i + 5 ``` And I'm not just interested in this int example, I was looking for something clean and general, not overriding every int and string method. Thanks, sunqiang. That's just w...
This should do what you need: ``` class IntContainer(object): def __init__(self, x): self.x = x def __add__(self, other): # do some type checking on other return self.x + other def __radd__(self, other): # do some type checking on other return self.x + other ``` O...
How to update the twisted framework
1,117,255
3
2009-07-12T23:59:35Z
1,257,261
16
2009-08-10T21:15:38Z
[ "python", "twisted" ]
I can see from the latest 8.2 (almost 1200 lines of code) twisted that I am missing something: <http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/jabber/xmlstream.py> My copy (697 lines from 3 years ago) is in: /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/twisted/words/p...
Try using `virtualenv` and `pip` (`sudo easy_install virtualenv pip`), which are great ways to avoid the dependency hell that you are experiencing. With `virtualenv` you can create isolated Python environments, and then using `pip` you can directly install new packages into you `virtualenv`s. Here is a complete examp...
Cleaning up nested Try/Excepts
1,117,460
4
2009-07-13T01:51:59Z
1,117,507
9
2009-07-13T02:25:23Z
[ "python" ]
I've just written a chunk of code that strikes me as being far more nested than is optimal. I'd like advice on how to improve the style of this, particularly so that it conforms more with "Flat is better than nested." ``` for app in apps: if app.split('.', 1)[0] == 'zc': #only look for cron in zc apps try:...
The main problem is that your try clauses are too broad, particularly the outermost one: with that kind of habit, you WILL sooner or later run into a mysterious bug because one of your try/except has accidentally hidden an unexpected exception "bubbling up" from some other function you're calling. So I'd suggest, inst...
Set Django IntegerField by choices=... name
1,117,564
62
2009-07-13T03:05:15Z
1,117,586
7
2009-07-13T03:23:26Z
[ "python", "django", "django-models" ]
When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value? Consider this model: ``` class Thing(models.Model): PRIORITIES = ( (0, 'Low'), (...
I'd probably set up the reverse-lookup dict once and for all, but if I hadn't I'd just use: ``` thing.priority = next(value for value, name in Thing.PRIORITIES if name=='Normal') ``` which seems simpler than building the dict on the fly just to toss it away again;-).
Set Django IntegerField by choices=... name
1,117,564
62
2009-07-13T03:05:15Z
1,117,587
103
2009-07-13T03:23:48Z
[ "python", "django", "django-models" ]
When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value? Consider this model: ``` class Thing(models.Model): PRIORITIES = ( (0, 'Low'), (...
Do as [seen here](http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/). Then you can use a word that represents the proper integer. Like so: ``` LOW = 0 NORMAL = 1 HIGH = 2 STATUS_CHOICES = ( (LOW, 'Low'), (NORMAL, 'Normal'), (HIGH, 'High'), ) ``` Then they are still integers in the DB. U...
Python MySQLdb exceptions
1,117,828
7
2009-07-13T05:31:22Z
1,118,129
13
2009-07-13T07:38:08Z
[ "python", "mysql", "exception" ]
Just starting to get to grips with python and MySQLdb and was wondering 1. Where is the best play to put a try/catch block for the connection to MySQL. At the MySQLdb.connect point? Also should there be one when ever i query? 2. What exceptions should i be catching on any of these blocks? thanks for any help Cheers ...
Catch the MySQLdb.Error, while connecting and while executing query
How Do I Use Raw Socket in Python?
1,117,958
30
2009-07-13T06:36:13Z
1,118,003
8
2009-07-13T06:52:13Z
[ "python", "sockets", "raw-sockets" ]
I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack. I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would...
Sockets system calls (or Winsocks, on Windows), are already wrapped in the standard module `socket`: [intro](http://docs.python.org/howto/sockets.html), [reference](http://docs.python.org/library/socket.html). I've never used raw sockets but it looks like they can be used with this module: > The last example shows ho...
How Do I Use Raw Socket in Python?
1,117,958
30
2009-07-13T06:36:13Z
6,374,862
35
2011-06-16T15:57:17Z
[ "python", "sockets", "raw-sockets" ]
I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack. I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would...
You do it like this: First you disable your network card's automatic checksumming: ``` sudo ethtool -K eth1 tx off ``` And then send your dodgy frame from python: ``` #!/usr/bin/env python from socket import socket, AF_PACKET, SOCK_RAW s = socket(AF_PACKET, SOCK_RAW) s.bind(("eth1", 0)) # We're putting together an...
Turbogears 2 vs Django - any advice on choosing replacement for Turbogears 1?
1,118,163
10
2009-07-13T07:49:39Z
1,118,670
9
2009-07-13T10:18:12Z
[ "python", "django", "google-app-engine", "turbogears", "turbogears2" ]
I have been using Turbogears 1 for prototyping small sites for the last couple of years and it is getting a little long in the tooth. Any suggestions on making the call between upgrading to Turbogears 2 or switching to something like Django? I'm torn between the familiarity of the TG community who are pretty responsive...
I have experience with both Django and TG1.1. IMO, TurboGears strong point is it's ORM: SQLAlchemy. I prefer TurboGears when the database side of things is non-trivial. Django's ORM is just not that flexible and powerful. That being said, I prefer Django. If the database schema is a good fit with Django's ORM I woul...
Turbogears 2 vs Django - any advice on choosing replacement for Turbogears 1?
1,118,163
10
2009-07-13T07:49:39Z
1,118,673
13
2009-07-13T10:19:12Z
[ "python", "django", "google-app-engine", "turbogears", "turbogears2" ]
I have been using Turbogears 1 for prototyping small sites for the last couple of years and it is getting a little long in the tooth. Any suggestions on making the call between upgrading to Turbogears 2 or switching to something like Django? I'm torn between the familiarity of the TG community who are pretty responsive...
TG2 is built on top of Pylons which has a fairly large community as well. TG got faster compared to TG1 and it includes a per-method (not just web pages) caching engine. I think it's more AJAX-friendly than Django by the way pages can be easly published in HTML or JSON . 2011 update: after 3 years of bloated framework...
How to debug in Django, the good way?
1,118,183
378
2009-07-13T07:57:02Z
1,118,271
345
2009-07-13T08:29:24Z
[ "python", "django", "debugging" ]
So, I started learning to code in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29) and later [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some ...
There are a bunch of ways to do it, but the most straightforward is to simply use the [Python debugger](https://docs.python.org/2/library/pdb.html). Just add following line in to a Django view function: ``` import pdb; pdb.set_trace() ``` If you try to load that page in your browser, the browser will hang and you get...
How to debug in Django, the good way?
1,118,183
378
2009-07-13T07:57:02Z
1,118,273
64
2009-07-13T08:30:07Z
[ "python", "django", "debugging" ]
So, I started learning to code in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29) and later [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some ...
There are a few tools that cooperate well and can make your debugging task easier. Most important is the [Django debug toolbar](https://github.com/django-debug-toolbar/django-debug-toolbar). Then you need good logging using the Python [logging](http://docs.python.org/library/logging.html#module-logging) facility. You...
How to debug in Django, the good way?
1,118,183
378
2009-07-13T07:57:02Z
1,118,314
13
2009-07-13T08:40:54Z
[ "python", "django", "debugging" ]
So, I started learning to code in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29) and later [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some ...
I use [pyDev](http://www.pydev.sourceforge.net/) with Eclipse really good, set break points, step into code, view values on any objects and variables, try it.
How to debug in Django, the good way?
1,118,183
378
2009-07-13T07:57:02Z
1,118,360
181
2009-07-13T08:54:44Z
[ "python", "django", "debugging" ]
So, I started learning to code in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29) and later [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some ...
I really like [Werkzeug](http://werkzeug.pocoo.org/)'s interactive debugger. It's similar to Django's debug page, except that you get an interactive shell on every level of the traceback. If you use the [django-extensions](https://github.com/django-extensions/django-extensions), you get a `runserver_plus` managment com...
How to debug in Django, the good way?
1,118,183
378
2009-07-13T07:57:02Z
2,324,210
138
2010-02-24T06:52:09Z
[ "python", "django", "debugging" ]
So, I started learning to code in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29) and later [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some ...
A little quickie for template tags: ``` @register.filter def pdb(element): import pdb; pdb.set_trace() return element ``` Now, inside a template you can do `{{ template_var|pdb }}` and enter a pdb session (given you're running the local devel server) where you can inspect `element` to your heart's content. ...
How to debug in Django, the good way?
1,118,183
378
2009-07-13T07:57:02Z
2,324,303
33
2010-02-24T07:25:16Z
[ "python", "django", "debugging" ]
So, I started learning to code in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29) and later [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some ...
Almost everything has been mentioned so far, so I'll only add that instead of `pdb.set_trace()` one can use **ipdb.set\_trace()** which uses iPython and therefore is more powerful (autocomplete and other goodies). This requires ipdb package, so you only need to `pip install ipdb`
How to debug in Django, the good way?
1,118,183
378
2009-07-13T07:57:02Z
3,466,951
34
2010-08-12T11:07:32Z
[ "python", "django", "debugging" ]
So, I started learning to code in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29) and later [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some ...
I use [PyCharm](http://www.jetbrains.com/pycharm/) (same pydev engine as eclipse). Really helps me to visually be able to step through my code and see what is happening.
How to debug in Django, the good way?
1,118,183
378
2009-07-13T07:57:02Z
6,880,214
21
2011-07-30T00:11:18Z
[ "python", "django", "debugging" ]
So, I started learning to code in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29) and later [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some ...
I've pushed `django-pdb` to [PyPI](http://pypi.python.org/pypi/django-pdb). It's a simple app that means you don't need to edit your source code every time you want to break into pdb. Installation is just... 1. `pip install django-pdb` 2. Add `'django_pdb'` to your `INSTALLED_APPS` You can now run: `manage.py runser...
How to debug in Django, the good way?
1,118,183
378
2009-07-13T07:57:02Z
10,039,794
17
2012-04-06T06:09:44Z
[ "python", "django", "debugging" ]
So, I started learning to code in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29) and later [Django](http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29). The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some ...
The easiest way to debug python - especially for programmers that are used to Visual Studio - is using PTVS (Python Tools for Visual Studio). The steps are simple: 1. Download and install it from <http://pytools.codeplex.com/> 2. Set breakpoints and press F5. 3. Your breakpoint is hit, you can view/change the variable...
Is there a way to know which versions of python are supported by my code?
1,118,208
3
2009-07-13T08:05:03Z
1,118,220
7
2009-07-13T08:09:04Z
[ "python", "dependencies", "versioning" ]
You may know the Windows compliance tool that helps people to know if their code is supported by any version of the MS OS. I am looking something similar for Python. I am writing a lib with Python 2.6 and I realized that it was not compatible with Python 2.5 due to the use of the with keyword. I would like to know i...
In response to [a previous question about this](http://stackoverflow.com/questions/804538/tool-to-determine-what-lowest-version-of-python-required), I wrote [pyqver](http://github.com/ghewgill/pyqver/tree/master). If you have any improvements, please feel free to fork and contribute!
Non-Standard Optional Argument Defaults
1,118,454
3
2009-07-13T09:23:48Z
1,118,467
19
2009-07-13T09:26:54Z
[ "python", "optional-arguments" ]
I have two functions: ``` def f(a,b,c=g(b)): blabla def g(n): blabla ``` `c` is an optional argument in function `f`. If the user does not specify its value, the program should compute g(b) and that would be the value of `c`. But the code does not compile - it says name 'b' is not defined. How to fix that? ...
``` def f(a,b,c=None): if c is None: c = g(b) ``` If `None` can be a valid value for `c` then you do this: ``` sentinel = object() def f(a,b,c=sentinel): if c is sentinel: c = g(b) ```
Migrating Django Application to Google App Engine?
1,118,761
9
2009-07-13T10:40:05Z
1,119,377
8
2009-07-13T13:16:36Z
[ "python", "django", "google-app-engine" ]
I'm developing a web application and considering Django, Google App Engine, and several other options. I wondered what kind of "penalty" I will incur if I develop a complete Django application assuming it runs on a dedicated server, and then later want to migrate it to Google App Engine. I have a basic understanding o...
Most (all?) of Django is available in GAE, so your main task is to avoid basing your designs around a reliance on anything from Django or the Python standard libraries which is not available on GAE. You've identified the glaring difference, which is the database, so I'll assume you're on top of that. Another differenc...
PyQt: event is not triggered, what's wrong with my code?
1,119,110
4
2009-07-13T12:14:45Z
1,119,407
11
2009-07-13T13:20:59Z
[ "python", "pyqt" ]
I'm a Python newbie and I'm trying to write a trivial app with an event handler that gets activated when an item in a custom QTreeWidget is clicked. For some reason it doesn't work. Since I'm only at the beginning of learning it, I can't figure out what I'm doing wrong. Here is the code: ``` #!/usr/bin/env python imp...
You should have said ``` self.connect(self, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.onClick) ``` Notice it says **int** rather than *column* in the first argument to `SIGNAL`. You also only need to do the `connect` call once for the tree widget, not once for each node in the tree.
Live RX and TX rates in linux
1,119,683
2
2009-07-13T14:12:37Z
1,119,916
9
2009-07-13T14:50:05Z
[ "c++", "python", "c" ]
I'm looking for a way to programatically (whether calling a library, or a standalone program) monitor live ip traffic in linux. I don't want totals, i want the current bandwidth that is being used. I'm looking for a tool similar (but non-graphical) to OS X's istat menu's network traffic monitor. I'm fairly certain som...
We have byte and packet counters in /proc/net/dev, so: ``` import time last={} def diff(col): return counters[col] - last[iface][col] while True: print "\n%10s: %10s %10s %10s %10s"%("interface","bytes recv","bytes sent", "pkts recv", "pkts sent") for line in open('/proc/net/dev').readlines()[2:]: iface, co...
Java Python Integration
1,119,696
32
2009-07-13T14:15:23Z
1,119,711
24
2009-07-13T14:17:25Z
[ "java", "python", "integration" ]
I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate wi...
Why not use [Jython](http://www.jython.org/)? The only downside I can immediately think of is if your library uses CPython native extensions. EDIT: If you can use Jython *now* but think you may have problems with a later version of the library, I suggest you try to isolate the library from your app (e.g. some sort of ...
Java Python Integration
1,119,696
32
2009-07-13T14:15:23Z
1,119,884
10
2009-07-13T14:44:27Z
[ "java", "python", "integration" ]
I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate wi...
Frankly **most ways to somehow run Python directly from within JVM don't work**. They are either not-quite-compatible (new release of your third party library can use python 2.6 features and will not work with Jython 2.5) or hacky (it will break with cryptic JVM stacktrace not really leading to solution). **My preferr...
Base 62 conversion
1,119,722
56
2009-07-13T14:19:41Z
1,119,769
106
2009-07-13T14:27:01Z
[ "python", "math", "base62" ]
How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'). I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and ...
There is no standard module for this, but I have written my own functions to achieve that. ``` BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" def encode(num, alphabet=BASE62): """Encode a positive number in Base X Arguments: - `num`: The number to encode - `alphabet`: The a...
Base 62 conversion
1,119,722
56
2009-07-13T14:19:41Z
1,487,304
8
2009-09-28T14:20:24Z
[ "python", "math", "base62" ]
How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'). I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and ...
The following decoder-maker works with any reasonable base, has a much tidier loop, and gives an explicit error message when it meets an invalid character. ``` def base_n_decoder(alphabet): """Return a decoder for a base-n encoded string Argument: - `alphabet`: The alphabet used for encoding """ ba...
Base 62 conversion
1,119,722
56
2009-07-13T14:19:41Z
2,549,514
38
2010-03-30T23:58:33Z
[ "python", "math", "base62" ]
How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'). I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and ...
I once wrote a script to do this aswell, I think it's quite elegant :) ``` import string BASE_LIST = string.digits + string.letters + '_@' BASE_DICT = dict((c, i) for i, c in enumerate(BASE_LIST)) def base_decode(string, reverse_base=BASE_DICT): length = len(reverse_base) ret = 0 for i, c in enumerate(str...
Disabling Python nosetests
1,120,148
30
2009-07-13T15:27:28Z
1,843,106
107
2009-12-03T21:39:10Z
[ "python", "nosetests" ]
When using nosetests for Python it is possible to disable a unit test by setting the test function's `__test__` attribute to false. I have implemented this using the following decorator: ``` def unit_test_disabled(): def wrapper(func): func.__test__ = False return func return wrapper @unit_...
Nose already has a builtin decorator for this: ``` from nose.tools import nottest @nottest def test_my_sample_test() #code here ... ``` Also check out the other goodies that nose provides: <https://nose.readthedocs.org/en/latest/testing_tools.html>
Disabling Python nosetests
1,120,148
30
2009-07-13T15:27:28Z
7,687,714
25
2011-10-07T13:08:28Z
[ "python", "nosetests" ]
When using nosetests for Python it is possible to disable a unit test by setting the test function's `__test__` attribute to false. I have implemented this using the following decorator: ``` def unit_test_disabled(): def wrapper(func): func.__test__ = False return func return wrapper @unit_...
There also is a skiptest plugin for nosetest, which will cause the test show in test output as skipped. Here is a decorator for that: ``` def skipped(func): from nose.plugins.skip import SkipTest def _(): raise SkipTest("Test %s is skipped" % func.__name__) _.__name__ = func.__name__ return _ `...
Disabling Python nosetests
1,120,148
30
2009-07-13T15:27:28Z
28,630,874
38
2015-02-20T14:06:06Z
[ "python", "nosetests" ]
When using nosetests for Python it is possible to disable a unit test by setting the test function's `__test__` attribute to false. I have implemented this using the following decorator: ``` def unit_test_disabled(): def wrapper(func): func.__test__ = False return func return wrapper @unit_...
You can also use [`unittest.skip`](https://docs.python.org/2/library/unittest.html#unittest.skip) decorator: ``` import unittest @unittest.skip("temporarily disabled") class MyTestCase(unittest.TestCase): ... ```
How do you cast an instance to a derived class?
1,120,156
5
2009-07-13T15:28:24Z
1,120,278
7
2009-07-13T15:45:51Z
[ "python", "oop", "inheritance" ]
I am trying to use a little inheritance in a Python program I am working on. I have a base class, User, which implements all of the functionality of a user. I am adding the concept of an unapproved user, which is just like a user, with the addition of a single method. The User class has some methods that return a User...
Rather than "casting", I think you really want to create an `UnapprovedUser` rather than a `User` when invoking `UnapprovedUser.get()`. To do that: Change `User.get` to actually use the `cls` argument that's passed-in: ``` @classmethod def get(cls, uid): ldap_data = LdapUtil.get(uid + ',' + self.base_dn) retu...
Does Jython have the GIL?
1,120,354
15
2009-07-13T15:58:36Z
1,120,370
19
2009-07-13T16:00:43Z
[ "python", "multithreading", "jython" ]
I was sure that it hasn't, but looking for a definite answer on the Interwebs left me in doubt. For example, I got a [2008 post](http://journal.thobe.org/2008/03/next-step-to-increase-python.html) which sort of looked like a joke at first glance but seemed to be serious at looking closer. *Edit:* **... and turned out ...
No, it does not. It's a part of the VM implementation, not the language. See also: ``` from __future__ import braces ```
Does Jython have the GIL?
1,120,354
15
2009-07-13T15:58:36Z
1,147,548
22
2009-07-18T13:35:07Z
[ "python", "multithreading", "jython" ]
I was sure that it hasn't, but looking for a definite answer on the Interwebs left me in doubt. For example, I got a [2008 post](http://journal.thobe.org/2008/03/next-step-to-increase-python.html) which sort of looked like a joke at first glance but seemed to be serious at looking closer. *Edit:* **... and turned out ...
The quote you found was indeed a joke, here is a demo of Jython's implementation of the GIL: ``` Jython 2.5.0 (trunk:6550M, Jul 20 2009, 08:40:15) [Java HotSpot(TM) Client VM (Apple Inc.)] on java1.5.0_19 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import GIL File "<st...
Using Python to execute a command on every file in a folder
1,120,707
23
2009-07-13T16:50:53Z
1,120,736
41
2009-07-13T16:55:06Z
[ "python", "foreach", "mencoder" ]
I'm trying to create a Python script that would : 1. Look into the folder "/input" 2. For each video in that folder, run a mencoder command (to transcode them to something playable on my phone) 3. Once mencoder has finished his run, delete the original video. That doesn't seem too hard, but I suck at python :) Any i...
To find all the filenames use `os.listdir()`. Then you loop over the filenames. Like so: ``` import os for filename in os.listdir('dirname'): callthecommandhere(blablahbla, filename, foo) ``` If you prefer subprocess, use subprocess. :-)
Using Python to execute a command on every file in a folder
1,120,707
23
2009-07-13T16:50:53Z
1,120,770
15
2009-07-13T17:01:45Z
[ "python", "foreach", "mencoder" ]
I'm trying to create a Python script that would : 1. Look into the folder "/input" 2. For each video in that folder, run a mencoder command (to transcode them to something playable on my phone) 3. Once mencoder has finished his run, delete the original video. That doesn't seem too hard, but I suck at python :) Any i...
Use [os.walk](http://docs.python.org/library/os.html#os.walk) to iterate recursively over directory content: ``` import os root_dir = '.' for directory, subdirectories, files in os.walk(root_dir): for file in files: print os.path.join(directory, file) ``` No real difference between os.system and subproc...
Using Python to execute a command on every file in a folder
1,120,707
23
2009-07-13T16:50:53Z
1,121,416
9
2009-07-13T18:58:39Z
[ "python", "foreach", "mencoder" ]
I'm trying to create a Python script that would : 1. Look into the folder "/input" 2. For each video in that folder, run a mencoder command (to transcode them to something playable on my phone) 3. Once mencoder has finished his run, delete the original video. That doesn't seem too hard, but I suck at python :) Any i...
Python might be overkill for this. ``` for file in *; do mencoder -some options $file; rm -f $file ; done ```
Which is better in python, del or delattr?
1,120,927
99
2009-07-13T17:33:33Z
1,120,938
12
2009-07-13T17:34:59Z
[ "python", "del" ]
This may be silly, but its been nagging the back of my brain for a while. Python gives us two built-in ways to delete attributes from objects, the **del** command word and the **delattr** built-in function. I prefer **delattr** because it I think its a bit more explicit: ``` del foo.bar delattr(foo, "bar") ``` But I...
It's really a matter of preference, but the first is probably preferable. I'd only use the second one if you don't know the name of the attribute that you're deleting ahead of time.
Which is better in python, del or delattr?
1,120,927
99
2009-07-13T17:33:33Z
1,121,036
15
2009-07-13T17:55:06Z
[ "python", "del" ]
This may be silly, but its been nagging the back of my brain for a while. Python gives us two built-in ways to delete attributes from objects, the **del** command word and the **delattr** built-in function. I prefer **delattr** because it I think its a bit more explicit: ``` del foo.bar delattr(foo, "bar") ``` But I...
Unquestionably the former. In my view this is like asking whether `foo.bar` is better than `getattr(foo, "bar")`, and I don't think anyone is asking that question :)
Which is better in python, del or delattr?
1,120,927
99
2009-07-13T17:33:33Z
1,121,068
161
2009-07-13T17:58:51Z
[ "python", "del" ]
This may be silly, but its been nagging the back of my brain for a while. Python gives us two built-in ways to delete attributes from objects, the **del** command word and the **delattr** built-in function. I prefer **delattr** because it I think its a bit more explicit: ``` del foo.bar delattr(foo, "bar") ``` But I...
The first is more efficient than the second. `del foo.bar` compiles to two bytecode instructions: ``` 2 0 LOAD_FAST 0 (foo) 3 DELETE_ATTR 0 (bar) ``` whereas `delattr(foo, "bar")` takes five: ``` 2 0 LOAD_GLOBAL 0 (delattr) ...
Which is better in python, del or delattr?
1,120,927
99
2009-07-13T17:33:33Z
19,380,479
17
2013-10-15T11:49:04Z
[ "python", "del" ]
This may be silly, but its been nagging the back of my brain for a while. Python gives us two built-in ways to delete attributes from objects, the **del** command word and the **delattr** built-in function. I prefer **delattr** because it I think its a bit more explicit: ``` del foo.bar delattr(foo, "bar") ``` But I...
* **del** is more explicit and efficient; * **delattr** allows dynamic attribute deleting. Consider the following examples: ``` for name in ATTRIBUTES: delattr(obj, name) ``` or: ``` def _cleanup(self, name): """Do cleanup for an attribute""" value = getattr(self, name) self._pre_cleanup(name, value...
List comprehension python
1,122,612
2
2009-07-13T23:11:11Z
1,122,653
9
2009-07-13T23:21:24Z
[ "python", "lisp", "list-comprehension" ]
What is the equivalent list comprehension in python of the following Common Lisp code: ``` (loop for x = input then (if (evenp x) (/ x 2) (+1 (* 3 x))) collect x until (= x 1)) ```
I believe you are writing the hailstone sequence, although I could be wrong since I am not fluent in Lisp. As far as I know, you can't do this in only a list comprehension, since each element depends on the last. How I would do it would be this ``` def hailstone(n): yield n while n!=1 if n%2 == 0: # ...
List comprehension python
1,122,612
2
2009-07-13T23:11:11Z
1,122,663
10
2009-07-13T23:24:13Z
[ "python", "lisp", "list-comprehension" ]
What is the equivalent list comprehension in python of the following Common Lisp code: ``` (loop for x = input then (if (evenp x) (/ x 2) (+1 (* 3 x))) collect x until (= x 1)) ```
A list comprehension is used to take an existing sequence and perform some function and/or filter to it, resulting in a new list. So, in this case a list comprehension is not appropriate since you don't have a starting sequence. An example with a while loop: ``` numbers = [] x=input() while x != 1: numbers.append(x)...
Is it acceptable to use tricks to save programmer when putting data in your code?
1,122,691
9
2009-07-13T23:34:04Z
1,122,710
32
2009-07-13T23:38:17Z
[ "python", "coding-style" ]
Example: It's really annoying to type a list of strings in python: ``` ["January", "February", "March", "April", ...] ``` I often do something like this to save me having to type quotation marks all over the place: ``` "January February March April May June July August ...".split() ``` Those took the same amount of...
Code is usually read many times, and it is written only once. Saving writing time at the expense of readability is not usually a good choice, unless you are doing some throw-away code. The second version is less explicit, and you need some time to understand what the code is doing. And we are simply talking about va...
Is it acceptable to use tricks to save programmer when putting data in your code?
1,122,691
9
2009-07-13T23:34:04Z
1,122,737
19
2009-07-13T23:50:07Z
[ "python", "coding-style" ]
Example: It's really annoying to type a list of strings in python: ``` ["January", "February", "March", "April", ...] ``` I often do something like this to save me having to type quotation marks all over the place: ``` "January February March April May June July August ...".split() ``` Those took the same amount of...
A good text editor can make these things a non-issue. For example, I can type the following line in my code: ``` print `"January February March April May June July August September October November December".split()` ``` And then using the key sequence `V:!python<ENTER>` I can run the line through the python interpre...
Does Python have anonymous classes?
1,123,000
51
2009-07-14T01:22:55Z
1,123,026
37
2009-07-14T01:32:06Z
[ "python" ]
I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet: ``` var foo = new { x = 1, y = 2 }; var bar = new { y = 2, x = 1 }; foo.Equals(bar); // "true" ``` In Python, I would imagine something like this: ``` foo = record(x = 1, y = 2) bar = record(y = 2, x =...
The pythonic way would be to use a `dict`: ``` >>> foo = dict(x=1, y=2) >>> bar = dict(y=2, x=1) >>> foo == bar True ``` Meets all your requirements except that you still have to do `foo['x']` instead of `foo.x`. If that's a problem, you could easily define a class such as: ``` class Bunch(object): def __init__...
Does Python have anonymous classes?
1,123,000
51
2009-07-14T01:22:55Z
1,123,054
19
2009-07-14T01:40:29Z
[ "python" ]
I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet: ``` var foo = new { x = 1, y = 2 }; var bar = new { y = 2, x = 1 }; foo.Equals(bar); // "true" ``` In Python, I would imagine something like this: ``` foo = record(x = 1, y = 2) bar = record(y = 2, x =...
1) See <http://uszla.me.uk/space/blog/2008/11/06>. You can create an anonymous object with slightly ugly syntax by using the `type` built-in function: ``` anon_object_2 = type("", (), {})() ``` where the 3rd parameter is the dict that will contain the fields of your object. ``` foo = type("", (), dict(y=1))() foo...
Does Python have anonymous classes?
1,123,000
51
2009-07-14T01:22:55Z
13,828,824
12
2012-12-11T21:29:13Z
[ "python" ]
I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet: ``` var foo = new { x = 1, y = 2 }; var bar = new { y = 2, x = 1 }; foo.Equals(bar); // "true" ``` In Python, I would imagine something like this: ``` foo = record(x = 1, y = 2) bar = record(y = 2, x =...
Looks like Python 3.3 has added exactly this thing in the form of [`types.SimpleNamespace`](http://docs.python.org/3/library/types.html#types.SimpleNamespace) class.
How to lock a critical section in Django?
1,123,200
13
2009-07-14T02:44:26Z
4,317,995
13
2010-11-30T20:04:39Z
[ "python", "django" ]
I can't find a good clean way to lock a critical section in Django. I could use a lock or semaphore but the python implementation is for threads only, so if the production server forks then those will not be respected. Does anyone know of a way (I am thinking posix semaphores right now) to guarantee a lock across proce...
If you use RDBMS, you can use its "LOCK" mechanism. For example, while one "SELECT FOR UPDATE" transaction locks a row, the other "SELECT FOR UPDATE" transactions with the row must wait. ``` # You can use any Python DB API. [SQL] BEGIN; [SQL] SELECT col_name FROM table_name where id = 1 FOR UPDATE; [Process some pyt...
Django: Converting an entire set of a Model's objects into a single dictionary
1,123,337
57
2009-07-14T03:35:53Z
1,123,350
25
2009-07-14T03:42:17Z
[ "python", "django", "django-models", "dictionary" ]
*If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.* Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this: ``` class DictModel(models.Model): key = models.CharF...
You are looking for the [Values member of QuerySet](http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-fields) which allows you to get a list of dictionaries from your query > Returns a ValuesQuerySet -- a QuerySet > that evaluates to a list of > dictionaries instead of model-instance > objects. Each of...
Django: Converting an entire set of a Model's objects into a single dictionary
1,123,337
57
2009-07-14T03:35:53Z
1,123,603
15
2009-07-14T05:35:57Z
[ "python", "django", "django-models", "dictionary" ]
*If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.* Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this: ``` class DictModel(models.Model): key = models.CharF...
Does this need to create an actual dict? could you get by with only something that looked like a dict? ``` class DictModelAdaptor(): def __init__(self, model): self.model = model def __getitem__(self, key): return self.model.objects.get(key=key) def __setitem__(self, key, item): p...
Django: Converting an entire set of a Model's objects into a single dictionary
1,123,337
57
2009-07-14T03:35:53Z
1,124,531
13
2009-07-14T10:19:23Z
[ "python", "django", "django-models", "dictionary" ]
*If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.* Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this: ``` class DictModel(models.Model): key = models.CharF...
You can use the `python` [serializer](http://docs.djangoproject.com/en/dev/topics/serialization): ``` from django.core import serializers data = serializers.serialize('python', DictModel.objects.all()) ```
Django: Converting an entire set of a Model's objects into a single dictionary
1,123,337
57
2009-07-14T03:35:53Z
1,124,610
16
2009-07-14T10:39:13Z
[ "python", "django", "django-models", "dictionary" ]
*If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.* Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this: ``` class DictModel(models.Model): key = models.CharF...
You want the `in_bulk` queryset method which, according to the docs: > Takes a list of primary-key values and > returns a dictionary mapping each > primary-key value to an instance of > the object with the given ID. It takes a list of IDs, so you'll need to get that first via the `values_list` method: ``` ids = MyMo...
Django: Converting an entire set of a Model's objects into a single dictionary
1,123,337
57
2009-07-14T03:35:53Z
1,677,068
208
2009-11-04T22:18:09Z
[ "python", "django", "django-models", "dictionary" ]
*If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.* Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this: ``` class DictModel(models.Model): key = models.CharF...
You can also rely on django code already written ;). ``` from django.forms.models import model_to_dict model_to_dict(instance, fields=[], exclude=[]) ```
"select" on multiple Python multiprocessing Queues?
1,123,855
16
2009-07-14T06:58:17Z
1,123,952
13
2009-07-14T07:27:44Z
[ "python", "events", "select", "synchronization", "multiprocessing" ]
What's the best way to wait (without spinning) until something is available in either one of two (multiprocessing) [Queues](http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue), where both reside on the same system?
It doesn't look like there's an official way to handle this yet. Or at least, not based on this: * <http://bugs.python.org/issue3831> You could try something like what this post is doing -- accessing the underlying pipe filehandles: * <http://haltcondition.net/?p=2319> and then use select.
"select" on multiple Python multiprocessing Queues?
1,123,855
16
2009-07-14T06:58:17Z
2,162,188
17
2010-01-29T13:29:15Z
[ "python", "events", "select", "synchronization", "multiprocessing" ]
What's the best way to wait (without spinning) until something is available in either one of two (multiprocessing) [Queues](http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue), where both reside on the same system?
Actually you can use multiprocessing.Queue objects in select.select. i.e. ``` que = multiprocessing.Queue() (input,[],[]) = select.select([que._reader],[],[]) ``` would select que only if it is ready to be read from. No documentation about it though. I was reading the source code of the multiprocessing.queue library...
How can I find path to given file?
1,124,810
2
2009-07-14T11:30:36Z
1,124,825
9
2009-07-14T11:33:23Z
[ "python" ]
I have a file, for example "something.exe" and I want to find path to this file How can I do this in python?
Perhaps `os.path.abspath()` would do it: ``` import os print os.path.abspath("something.exe") ``` If your `something.exe` is not in the current directory, you can pass any relative path and `abspath()` will resolve it.
How can I find path to given file?
1,124,810
2
2009-07-14T11:30:36Z
1,124,841
7
2009-07-14T11:36:46Z
[ "python" ]
I have a file, for example "something.exe" and I want to find path to this file How can I do this in python?
use [os.path.abspath](http://docs.python.org/library/os.path.html#os.path.abspath) to get a normalized absolutized version of the pathname use [os.walk](http://docs.python.org/library/os.html#os.walk) to get it's location ``` import os exe = 'something.exe' #if the exe just in current dir print os.path.abspath(exe) ...
Django persistent database connection
1,125,504
45
2009-07-14T13:47:00Z
1,175,140
17
2009-07-23T23:55:40Z
[ "python", "database", "django", "mod-wsgi", "persistent" ]
I'm using django with apache and mod\_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms). While...
In Django trunk, edit `django/db/__init__.py` and comment out the line: ``` signals.request_finished.connect(close_connection) ``` This signal handler causes it to disconnect from the database after every request. I don't know what all of the side-effects of doing this will be, but it doesn't make any sense to start ...
Django persistent database connection
1,125,504
45
2009-07-14T13:47:00Z
1,698,102
19
2009-11-08T22:15:33Z
[ "python", "database", "django", "mod-wsgi", "persistent" ]
I'm using django with apache and mod\_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms). While...
Try [PgBouncer](http://wiki.postgresql.org/wiki/PgBouncer) - a lightweight connection pooler for PostgreSQL. Features: * Several levels of brutality when rotating connections: + Session pooling + Transaction pooling + Statement pooling * Low memory requirements (2k per connection by default).