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
Sets module deprecated warning
2,040,616
23
2010-01-11T08:25:12Z
2,040,630
30
2010-01-11T08:30:10Z
[ "python" ]
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
Stop using the `sets` module, or switch to an older version of python where it's not deprecated. According to [pep-004](http://www.python.org/dev/peps/pep-0004/), `sets` is deprecated as of v2.6, replaced by the built-in [`set` and `frozenset` types](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset...
Sets module deprecated warning
2,040,616
23
2010-01-11T08:25:12Z
2,040,746
25
2010-01-11T08:58:44Z
[ "python" ]
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
History: Before Python 2.3: no set functionality Python 2.3: `sets` module arrived Python 2.4: `set` and `frozenset` built-ins introduced Python 2.6: `sets` module deprecated You should change your code to use `set` instead of `sets.Set`. If you still wish to be able to support using Python 2.3, you can do thi...
What is The Pythonic Way for writing matching algorithm
2,041,378
2
2010-01-11T11:08:04Z
2,041,419
8
2010-01-11T11:17:11Z
[ "python" ]
I have this piece of code (should be self-explanatory; if not, just ask): ``` for tr in completed_taskrevs: found = False for nr in completion_noterevs: if tr.description in nr.body: completion_noterevs.remove(nr) found = True break assert found ``` How can I ma...
Try this: ``` for tr in compleded_taskrevs: try: nrs = (nr for nr in completion_noterevs if tr.description in nr.body) completion_noterevs.remove(nrs.next()) except StopIteration: raise ValueError('Some error') ``` EDIT: Devin is right. Assertion is not the way to go, better to use a s...
How to copy a file from a network share to local disk with variables?
2,042,342
4
2010-01-11T14:16:58Z
2,042,376
9
2010-01-11T14:22:14Z
[ "python", "network-programming", "share" ]
If I use the following line: ``` shutil.copyfile(r"\\mynetworkshare\myfile.txt","C:\TEMP\myfile.txt") ``` everything works fine. However, what I can't seem to figure out is how to use a variable with the network share path, because I need the 'r' (relative?) flag. The end result I would imagine would be something lik...
The `r` used in your first code example is making the string a "raw" string. In this example, that means the string will see the backslashes and not try to use them to escape `\\` to just `\`. To get your second code sample working, you'd use the `r` on the strings, and not in the `copyfile` command: ``` source_path ...
A more pythonic way of iterating a list while excluding an element each iteration
2,042,363
10
2010-01-11T14:20:04Z
2,042,394
17
2010-01-11T14:28:04Z
[ "python" ]
I have the following code: ``` items = ["one", "two", "three"] for i in range(0, len(items)): for index, element in enumerate(items): if index != i: # do something with element ``` Basically I want to exclude every element once and iterate the rest. So for the list I have above, I'd like the ...
Although upvoted like crazy, my first solution wasn't what the OP wanted, which is N lists, each missing exactly one of the N original elements: ``` >>> from itertools import combinations >>> L = ["one", "two", "three", "four"] >>> for R in combinations(L, len(L) - 1): ... print " and ".join(R) ... one and two and...
compile python .py file without executing
2,042,426
24
2010-01-11T14:34:44Z
2,042,442
41
2010-01-11T14:39:28Z
[ "python" ]
Is there a way to compile a Python .py file from the command-line **without** executing it? I am working with an application that stores its python extensions in a non-standard path with limited permissions and I'd like to compile the files during installation. I don't need the overhead of Distutils.
> The [py\_compile](http://docs.python.org/library/py_compile.html) module provides a function to generate a byte-code file from a source file, and another function used when the module source file is invoked as a script. ``` python -m py_compile fileA.py fileB.py fileC.py ```
compile python .py file without executing
2,042,426
24
2010-01-11T14:34:44Z
2,042,458
8
2010-01-11T14:41:38Z
[ "python" ]
Is there a way to compile a Python .py file from the command-line **without** executing it? I am working with an application that stores its python extensions in a non-standard path with limited permissions and I'd like to compile the files during installation. I don't need the overhead of Distutils.
Yes, there is module compileall: <http://docs.python.org/library/compileall.html#module-compileall> Here's an example that compiles all the `.py` files in a directory (but not sub-directories) ``` python -m compileall -l myDirectory ```
Executing Python multi-line statements in the one-line command-line
2,043,453
84
2010-01-11T17:11:27Z
2,043,472
10
2010-01-11T17:14:19Z
[ "python", "shell", "command-line", "heredoc" ]
I'm using Python with `-c` to execute a one-liner loop, i.e.: ``` $ python -c "for r in range(10): print 'rob'" ``` This works fine. However, if I import a module before the for loop, I get a syntax error: ``` $ python -c "import sys; for r in range(10): print 'rob'" File "<string>", line 1 import sys; for r i...
just use return and type it on the next line: ``` user@host:~$ python -c "import sys > for r in range(10): print 'rob'" rob rob ... ```
Executing Python multi-line statements in the one-line command-line
2,043,453
84
2010-01-11T17:11:27Z
2,043,499
72
2010-01-11T17:18:43Z
[ "python", "shell", "command-line", "heredoc" ]
I'm using Python with `-c` to execute a one-liner loop, i.e.: ``` $ python -c "for r in range(10): print 'rob'" ``` This works fine. However, if I import a module before the for loop, I get a syntax error: ``` $ python -c "import sys; for r in range(10): print 'rob'" File "<string>", line 1 import sys; for r i...
you could do ``` echo -e "import sys\nfor r in range(10): print 'rob'" | python ``` or w/out pipes: ``` python -c "exec(\"import sys\\nfor r in range(10): print 'rob'\")" ``` or ``` (echo "import sys" ; echo "for r in range(10): print 'rob'") | python ``` or @[SilentGhost's answer](http://stackoverflow.com/questi...
Executing Python multi-line statements in the one-line command-line
2,043,453
84
2010-01-11T17:11:27Z
2,043,503
7
2010-01-11T17:19:27Z
[ "python", "shell", "command-line", "heredoc" ]
I'm using Python with `-c` to execute a one-liner loop, i.e.: ``` $ python -c "for r in range(10): print 'rob'" ``` This works fine. However, if I import a module before the for loop, I get a syntax error: ``` $ python -c "import sys; for r in range(10): print 'rob'" File "<string>", line 1 import sys; for r i...
The problem is not with the `import` statement. The problem is that the control flow statements don't work inlined in a python command. Replace that `import` statement with any other statement and you'll see the same problem. Think about it: python can't possibly inline everything. It uses indentation to group control...
Executing Python multi-line statements in the one-line command-line
2,043,453
84
2010-01-11T17:11:27Z
2,043,633
23
2010-01-11T17:39:30Z
[ "python", "shell", "command-line", "heredoc" ]
I'm using Python with `-c` to execute a one-liner loop, i.e.: ``` $ python -c "for r in range(10): print 'rob'" ``` This works fine. However, if I import a module before the for loop, I get a syntax error: ``` $ python -c "import sys; for r in range(10): print 'rob'" File "<string>", line 1 import sys; for r i...
The issue is not actually with the import statement, it's with anything being before the for loop. Or more specifically, anything appearing before an inlined block. For example, these all work: ``` python -c "import sys; print 'rob'" python -c "import sys; sys.stdout.write('rob\n')" ``` If import being a statement w...
Executing Python multi-line statements in the one-line command-line
2,043,453
84
2010-01-11T17:11:27Z
2,356,490
48
2010-03-01T14:38:57Z
[ "python", "shell", "command-line", "heredoc" ]
I'm using Python with `-c` to execute a one-liner loop, i.e.: ``` $ python -c "for r in range(10): print 'rob'" ``` This works fine. However, if I import a module before the for loop, I get a syntax error: ``` $ python -c "import sys; for r in range(10): print 'rob'" File "<string>", line 1 import sys; for r i...
this style can be used in makefiles too (and in fact it is used quite often). ``` python - <<EOF import sys for r in range(3): print 'rob' EOF ``` or ``` python - <<-EOF import sys for r in range(3): print 'rob' EOF ``` in latter case leading *tab characters* are removed too (and some structured outlook can...
Determine if directory is under git control
2,044,574
48
2010-01-11T20:07:43Z
2,044,677
35
2010-01-11T20:27:25Z
[ "python", "git" ]
How can I tell if a given directory is part of a git respository? (The following is in python, but bash or something would be fine.) ``` os.path.isdir('.svn') ``` will tell you if the current directory is controlled by Subversion. Mercurial and Git just have a .hg/.git at the top of the repository, so for `hg` I can...
In ruby, `system('git rev-parse')` will return true if the current directory is in a git repo, and false otherwise. I imagine the pythonic equivalent should work similarly. **EDIT:** Sure enough: ``` # in a git repo, running ipython >>> system('git rev-parse') 0 # not in a git repo >>> system('git rev-parse') 32768 ...
Determine if directory is under git control
2,044,574
48
2010-01-11T20:07:43Z
2,044,714
70
2010-01-11T20:33:46Z
[ "python", "git" ]
How can I tell if a given directory is part of a git respository? (The following is in python, but bash or something would be fine.) ``` os.path.isdir('.svn') ``` will tell you if the current directory is controlled by Subversion. Mercurial and Git just have a .hg/.git at the top of the repository, so for `hg` I can...
Just found this in `git help rev-parse` ``` git rev-parse --is-inside-work-tree ``` prints `true` if it is in the work tree, `false` if it's in the '.git' tree, and fatal error if it's neither. Both 'true' and 'false' are printed on stdout with an exit status of 0, the fatal error is printed on stderr with an exit st...
Pythonize Me: how to manage caller context variables in Python? (Python/Django)
2,044,941
4
2010-01-11T21:06:27Z
2,045,011
10
2010-01-11T21:18:18Z
[ "python", "django", "django-context" ]
I'm trying to refactor a fairly hefty view function in Django. There are too many variables floating around and it's a huge function. Ideally, I want to modularize the view into logical functions. However, I have to pass the function context around to get easy access to the variables. For example: ``` def complex_vi...
I like (d) - Create a class for it, and use member functions to do the work. In Django, a view is just a 'callable' that accepts an HTTPRequest object, and whatever other paramaters your URL routing passes to it. Python classes can be callable just like functions, if you define a `__call__` method on them, like this:...
Regex match even number of letters
2,045,175
4
2010-01-11T21:46:19Z
2,045,208
13
2010-01-11T21:51:21Z
[ "python", "regex" ]
I need to match an expression in Python with regular expressions that only matches even number of letter occurrences. For example: ``` AAA # no match AA # match fsfaAAasdf # match sAfA # match sdAAewAsA # match AeAiA # no match ``` An even number of As SHOULD match.
Try this regular expression: ``` ^[^A]*((AA)+[^A]*)*$ ``` And if the `A`s don’t need to be consecutive: ``` ^[^A]*(A[^A]*A[^A]*)*$ ```
django, location based searches
2,045,318
8
2010-01-11T22:08:36Z
2,045,361
7
2010-01-11T22:16:48Z
[ "python", "django", "geolocation", "geodjango" ]
Excuse my ignorance, I am not even sure of the correct term for this. What I want to do is search by city and state or zip code in my django application and also include results within certain distances of the location (25, 50, 75 miles). I am guessing you probably need to convert the city and state or zip code to lat...
You could use [GeoDjango](http://geodjango.org/), which already includes these features. Otherwise you can do exactly as you said: geocode addresses to get latitude and longitude, then just do the math ;-)
How to catch an exception in python and get a reference to the exception, WITHOUT knowing the type?
2,045,786
19
2010-01-11T23:51:30Z
2,045,828
31
2010-01-12T00:01:25Z
[ "python", "exception-handling", "jython" ]
I'm wondering how I can catch **any** raised object (i.e. a type that does not extend `Exception`), and still get a reference to it. I came across the desire to do this when using Jython. When calling a Java method, if that method raises an exception, it will not extend Python's `Exception` class, so a block like this...
You can reference exceptions using the [`sys`](http://docs.python.org/library/sys.html) module. [`sys.exc_info`](http://docs.python.org/library/sys.html#sys.exc_info) is a tuple of the type, the instance and the traceback. ``` import sys try: # some call to a java lib that raises an exception here except: ins...
How to catch an exception in python and get a reference to the exception, WITHOUT knowing the type?
2,045,786
19
2010-01-11T23:51:30Z
20,632,454
7
2013-12-17T11:04:26Z
[ "python", "exception-handling", "jython" ]
I'm wondering how I can catch **any** raised object (i.e. a type that does not extend `Exception`), and still get a reference to it. I came across the desire to do this when using Jython. When calling a Java method, if that method raises an exception, it will not extend Python's `Exception` class, so a block like this...
FWIW, I have found that if you add this import to your Jython script: ``` from java.lang import Exception ``` and just use the conventional Python Exception handler: ``` except Exception, e: ``` it will catch *both* Python exceptions *and* Java exceptions
PEP8 - 80 Characters - Big Integers
2,045,968
11
2010-01-12T00:45:19Z
2,045,984
21
2010-01-12T00:50:13Z
[ "python", "coding-style", "pep8" ]
This is somehow related to [question about big strings and PEP8](http://stackoverflow.com/questions/1874592/pep8-80-characters-big-strings). How can I make my script that has the following line PEP8 compliant ("Maximum Line Length" rule)? ``` pub_key = { 'e': 3226833362680126101036263622033066816222202666130162062...
> But most importantly: know when to be > inconsistent -- sometimes the style > guide just doesn't apply. When in > doubt, use your best judgment. [source](http://www.python.org/dev/peps/pep-0008/) In this case, I would just leave the big integers as is.
Tab Completion in Python Command Line Interface - how to catch Tab events
2,046,050
5
2010-01-12T01:11:57Z
2,046,054
15
2010-01-12T01:13:35Z
[ "python", "mercurial", "tab-completion", "raw-input" ]
I'm writing a little CLI in Python (as an extension to Mercurial) and would like to support tab-completion. Specifically, I would like catch tabs in the prompt and show a list of matching options (just like bash). Example: Enter section name: ``` ext*TAB* extensions extras ``` The problem is I'm not sure how ...
For that you use the [`readline`](http://docs.python.org/library/readline.html) module. Simplest code I can think: ``` import readline COMMANDS = ['extra', 'extension', 'stuff', 'errors', 'email', 'foobar', 'foo'] def complete(text, state): for cmd in COMMANDS: if cmd.startswith(text): ...
Getting String from A TextCtrl Box
2,046,338
7
2010-01-12T02:36:39Z
2,046,354
15
2010-01-12T02:41:08Z
[ "python", "wxpython", "textctrl" ]
I cannot seem to grasp how I would get the strings from a text Ctrl box. I am very new to this, so any help is greatly appricated. Here is the practic code: ``` import wx class citPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) wx.StaticText(self, -1, "Choo...
``` TextCtrlInstance.GetValue() ```
Is it possible to run function in a subprocess without threading or writing a separate file/script
2,046,603
34
2010-01-12T03:49:53Z
2,046,630
49
2010-01-12T03:57:13Z
[ "python", "function", "subprocess", "popen" ]
``` import subprocess def my_function(x): return x + 100 output = subprocess.Popen(my_function, 1) #I would like to pass the function object and its arguments print output #desired output: 101 ``` I have only found documentation on opening subprocesses using separate scripts. Does anyone know how to pass functi...
I think you're looking for something more like the multiprocessing module: <http://docs.python.org/library/multiprocessing.html#the-process-class> The subprocess module is for spawning processes and doing things with their input/output - not for running functions. Here is a `multiprocessing` version of your code: `...
Is it possible to run function in a subprocess without threading or writing a separate file/script
2,046,603
34
2010-01-12T03:49:53Z
2,046,633
8
2010-01-12T03:58:47Z
[ "python", "function", "subprocess", "popen" ]
``` import subprocess def my_function(x): return x + 100 output = subprocess.Popen(my_function, 1) #I would like to pass the function object and its arguments print output #desired output: 101 ``` I have only found documentation on opening subprocesses using separate scripts. Does anyone know how to pass functi...
You can use the standard Unix `fork` system call, as [`os.fork()`](http://docs.python.org/library/os.html#os.fork). `fork()` will create a new process, with the same script running. In the new process, it will return 0, while in the old process it will return the process ID of the new process. ``` child_pid = os.fork(...
What is/are the Python equivalent(s) to the Java Collections Framework?
2,047,220
4
2010-01-12T06:50:09Z
2,047,256
13
2010-01-12T06:55:49Z
[ "java", "c++", "python", "collections" ]
The Java Collections Framework is like the C++ Standard Template Library: "a unified architecture for representing and manipulating collections (objects that group multiple elements into a single unit)." <http://java.sun.com/docs/books/tutorial/collections/intro/index.html>
As it turns out, the equivalent to the Java Collections Framework in Python is... Python. All of the core collections featured in the Java Collections Framework are already present in core Python. Give it a try! Sequences provide lists, queues, stacks, etc. Dictionaries are your hash-tables and maps. Sets are present,...
What is/are the Python equivalent(s) to the Java Collections Framework?
2,047,220
4
2010-01-12T06:50:09Z
2,047,273
7
2010-01-12T06:58:27Z
[ "java", "c++", "python", "collections" ]
The Java Collections Framework is like the C++ Standard Template Library: "a unified architecture for representing and manipulating collections (objects that group multiple elements into a single unit)." <http://java.sun.com/docs/books/tutorial/collections/intro/index.html>
Other than the built-ins you might what to check out [collections](http://docs.python.org/library/collections.html?highlight=collections#module-collections). ``` >>> import collections >>> dir(collections) ['Callable', 'Container', 'Hashable', 'ItemsView', 'Iterable', 'Iterator', 'KeysView', 'Mapping', 'MappingView', ...
Is it possible to store Python class objects in SQLite?
2,047,814
17
2010-01-12T09:17:47Z
2,047,844
34
2010-01-12T09:22:47Z
[ "python", "sqlite", "serialization" ]
I would like to store Python objects into a [SQLite](http://en.wikipedia.org/wiki/SQLite) database. Is that possible? If so what would be some links / examples for it?
You can't store the object itself in the DB. What you do is to store the data from the object and reconstruct it later. A good way is to use the excellent [SQLAlchemy](http://www.sqlalchemy.org) library. It lets you map your defined class to a table in the database. Every mapped attribute will be stored, and can be us...
Is it possible to store Python class objects in SQLite?
2,047,814
17
2010-01-12T09:17:47Z
2,047,863
8
2010-01-12T09:26:00Z
[ "python", "sqlite", "serialization" ]
I would like to store Python objects into a [SQLite](http://en.wikipedia.org/wiki/SQLite) database. Is that possible? If so what would be some links / examples for it?
Yes it's possible but there are different approaches and which one is the suitable one, will depend on your requirements. * **Pickling** You can use the [pickle](http://docs.python.org/library/pickle.html) module to serialize objects, then store these objects in a blob in sqlite3 (or a textfield, if the dump is e.g...
How to plot a graph in Python?
2,048,041
5
2010-01-12T10:02:03Z
2,048,090
9
2010-01-12T10:10:02Z
[ "python", "matplotlib" ]
I have installed Matplotlib, and I have created two lists, x and y. I want the x-axis to have values from 0 to 100 in steps of 10 and the y-axis to have values from 0 to 1 in steps of 0.1. How do I plot this graph?
Have a look through the matplotlib [gallery](http://matplotlib.sourceforge.net/gallery.html), all the graphs there have their source code available. Find one you like, cut & paste, dissect!
Sql Alchemy What is wrong?
2,048,084
10
2010-01-12T10:09:17Z
2,048,136
16
2010-01-12T10:18:53Z
[ "python", "mysql", "sqlalchemy" ]
I got the tutorial > <http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html> When I compile got the error message ``` The debugged program raised the exception unhandled NameError "name 'BoundMetaData' is not defined" ``` I am use the latest sqlAlchemy . How Could I fixed this? After read this I modified to my o...
This tutorial is for SQLAlchemy version 0.2. Since the actual version is 0.5.7, I'd say the tutorial is severely outdated. Try the [official](http://www.sqlalchemy.org/docs/05/ormtutorial.html) one instead. --- **EDIT:** Now you have a completely different question. You should've asked another question instead of e...
Sql Alchemy What is wrong?
2,048,084
10
2010-01-12T10:09:17Z
11,069,954
17
2012-06-17T08:28:36Z
[ "python", "mysql", "sqlalchemy" ]
I got the tutorial > <http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html> When I compile got the error message ``` The debugged program raised the exception unhandled NameError "name 'BoundMetaData' is not defined" ``` I am use the latest sqlAlchemy . How Could I fixed this? After read this I modified to my o...
The fix for the tutorial is to just use `MetaData` instead of `BoundMetaData`. BoundMetaData is deprecated and replaced with MetaData. And to avoid getting such error in future, Try the [official](http://www.sqlalchemy.org/docs/05/ormtutorial.html) one instead, as `Nosklo` said. ``` from sqlalchemy import * db = cre...
PyQt4 signals and slots
2,048,098
5
2010-01-12T10:10:48Z
2,048,611
10
2010-01-12T11:44:46Z
[ "python", "qt", "qt4", "pyqt", "pyqt4" ]
I am writing my first Python app with PyQt4. I have a MainWindow and a Dialog class, which is a part of MainWindow class: ``` self.loginDialog = LoginDialog(); ``` I use slots and signals. Here's a connection made in MainWindow: ``` QtCore.QObject.connect(self.loginDialog, QtCore.SIGNAL("aa(str)"), self.login) ``` ...
You don't use the same signal, when emitting and connecting. `QtCore.SIGNAL("aa(str)")` is not the same as `QtCore.SIGNAL("aa")`. Signals must have the same signature. By the way, if you are defining your own signals, don't define parametres. Just write SIGNAL('aa'), because defining parametres is a thing from C++ and...
PyQt4 signals and slots
2,048,098
5
2010-01-12T10:10:48Z
7,618,282
26
2011-10-01T05:00:01Z
[ "python", "qt", "qt4", "pyqt", "pyqt4" ]
I am writing my first Python app with PyQt4. I have a MainWindow and a Dialog class, which is a part of MainWindow class: ``` self.loginDialog = LoginDialog(); ``` I use slots and signals. Here's a connection made in MainWindow: ``` QtCore.QObject.connect(self.loginDialog, QtCore.SIGNAL("aa(str)"), self.login) ``` ...
There are some concepts to be clarified **[QT signal & slot] VS [Python signal & slot]** All the predefined signals & slots provided by pyqt are implemented by QT's c++ code. Whenever you want to have a customized signal & slot in Python, it is a python signal & slot. Hence there are four cases to emits a signal to a...
Writing copyright information in python code
2,048,874
13
2010-01-12T12:30:18Z
2,048,889
9
2010-01-12T12:33:15Z
[ "python", "coding-style", "copyright-display" ]
What is the standard way of writing "copyright information" in python code? Should it be inside docstring or in block comments? I could not find it in PEPs.
``` # Comment in the beginning of the file ``` At least python built-in modules do this. (found out by doing `grep 'Copyright' /usr/lib64/python2.4/*.py`)
Writing copyright information in python code
2,048,874
13
2010-01-12T12:30:18Z
2,049,597
14
2010-01-12T14:27:32Z
[ "python", "coding-style", "copyright-display" ]
What is the standard way of writing "copyright information" in python code? Should it be inside docstring or in block comments? I could not find it in PEPs.
Some projects use module variables like `__license__`, as in: ``` __author__ = "Software Authors Name" __copyright__ = "Copyright (C) 2004 Author Name" __license__ = "Public Domain" __version__ = "1.0" ``` Seems like a pretty clean solution to me (unless you overdo it and dump epic texts into these variables), but on...
Why can't I pickle this object?
2,049,849
11
2010-01-12T15:01:04Z
2,050,357
25
2010-01-12T16:12:40Z
[ "python" ]
I have a class (below): ``` class InstrumentChange(object): '''This class acts as the DTO object to send instrument change information from the client to the server. See InstrumentChangeTransport below ''' def __init__(self, **kwargs): self.kwargs = kwargs self._changed = None d...
Your code has several minor "side" issues: the sudden appearance of a 'Transport' in the class name used in the test (it's not the class name that you're defining), the dubious trampling over built-in identifier `file` as a local variable (don't do that -- it doesn't hurt here, but the habit of trampling over built-in ...
Extract the fields of a C struct
2,050,318
12
2010-01-12T16:08:31Z
2,050,883
9
2010-01-12T17:20:45Z
[ "python", "c", "language-agnostic", "struct" ]
I often have to write code in other languages that interact with C structs. Most typically this involves writing Python code with the [struct](http://docs.python.org/library/struct.html) or [ctypes](http://docs.python.org/library/ctypes.html) modules. So I'll have a .h file full of struct definitions, and I have to ma...
If you compile your C code with debugging (`-g`), [pahole](http://fedorapeople.org/~acme/dwarves/) ([git](https://github.com/acmel/dwarves)) can give you the exact structure layouts being used. ``` $ pahole /bin/dd … struct option { const char * name; /* 0 8 */ int...
Appending the same string to a list of strings in Python
2,050,637
45
2010-01-12T16:50:17Z
2,050,649
76
2010-01-12T16:51:21Z
[ "python", "list" ]
I am trying to take one string, and append it to every string contained in a list, and then have a new list with the completed strings. Example: ``` list = ['foo', 'fob', 'faz', 'funk'] string = 'bar' *magic* list2 = ['foobar', 'fobbar', 'fazbar', 'funkbar'] ``` I tried for loops, and an attempt at list comprehensi...
The simplest way to do this is with a list comprehension: ``` [s + mystring for s in mylist] ``` Notice that I avoided using builtin names like `list` because that shadows or hides the builtin names, which is very much not good. Also, if you do not actually need a list, but just need an iterator, a generator express...
Appending the same string to a list of strings in Python
2,050,637
45
2010-01-12T16:50:17Z
2,050,721
8
2010-01-12T16:59:06Z
[ "python", "list" ]
I am trying to take one string, and append it to every string contained in a list, and then have a new list with the completed strings. Example: ``` list = ['foo', 'fob', 'faz', 'funk'] string = 'bar' *magic* list2 = ['foobar', 'fobbar', 'fazbar', 'funkbar'] ``` I tried for loops, and an attempt at list comprehensi...
``` my_list = ['foo', 'fob', 'faz', 'funk'] string = 'bar' my_new_list = [x + string for x in my_list] print my_new_list ``` This will print: ``` ['foobar', 'fobbar', 'fazbar', 'funkbar'] ```
Change dynamically the contents of a matplotlib plot
2,050,728
2
2010-01-12T17:00:29Z
2,051,151
7
2010-01-12T17:59:23Z
[ "python", "matplotlib", "plot" ]
I while ago, I was comparing the output of two functions using python and matplotlib. The result was as good as simple, since plotting with matplotlib is quite easy: I just plotted two arrays with different markers. Piece of cake. Now I find myself with the same problem, but now I have a lot of pair of curves to compa...
Well I managed to do it with an event handler for mouse clicks. I will change it for something more useful, but I post my solution anyway. ``` import matplotlib.pyplot as plt figure = plt.figure() # plotting plt.plot([1,2,3],[10,20,30],'bo-') plt.grid() plt.legend() def on_press(event): print 'you pressed', even...
why is this an infinite loop in python?
2,051,034
7
2010-01-12T17:40:27Z
2,051,045
36
2010-01-12T17:42:13Z
[ "python", "loops", "infinite-loop" ]
I can't seem to figure out why this is an infinite loop in python?? ``` for i in range(n): j=1 while((i*j)<n): j+=1 ``` shouldn't the outer loop go n times. incrementing j until its equal to n div i each time?
`i` starts at `0`, so the `while` condition stays always true; see the [range docs](http://docs.python.org/library/functions.html#range) for details.
why is this an infinite loop in python?
2,051,034
7
2010-01-12T17:40:27Z
2,051,049
7
2010-01-12T17:42:43Z
[ "python", "loops", "infinite-loop" ]
I can't seem to figure out why this is an infinite loop in python?? ``` for i in range(n): j=1 while((i*j)<n): j+=1 ``` shouldn't the outer loop go n times. incrementing j until its equal to n div i each time?
Because the initial value of `i` is 0.
why is this an infinite loop in python?
2,051,034
7
2010-01-12T17:40:27Z
2,051,052
12
2010-01-12T17:43:05Z
[ "python", "loops", "infinite-loop" ]
I can't seem to figure out why this is an infinite loop in python?? ``` for i in range(n): j=1 while((i*j)<n): j+=1 ``` shouldn't the outer loop go n times. incrementing j until its equal to n div i each time?
`i` starts at zero, so the condition for the inner loop is always `0*j < n`, which will always be true.
why is this an infinite loop in python?
2,051,034
7
2010-01-12T17:40:27Z
2,051,355
16
2010-01-12T18:27:06Z
[ "python", "loops", "infinite-loop" ]
I can't seem to figure out why this is an infinite loop in python?? ``` for i in range(n): j=1 while((i*j)<n): j+=1 ``` shouldn't the outer loop go n times. incrementing j until its equal to n div i each time?
You can create a "trace" showing the state changes of the variables. 1. n= 5; i= 0 2. n= 5; i= 0; j= 1 3. i\*j < n -> 0 < 5: n= 5; i= 0; j= 2 4. i\*j < n -> 0 < 5: n= 5; i= 0; j= 3 5. i\*j < n -> 0 < 5: n= 5; i= 0; j= 4 6. i\*j < n -> 0 < 5: n= 5; i= 0; j= 5 7. i\*j < n -> 0 < 5: n= 5; i= 0; j= 6 etc. You can prove ...
What is a Python egg?
2,051,192
280
2010-01-12T18:05:29Z
2,051,195
362
2010-01-12T18:06:42Z
[ "python", "egg" ]
I'm new to Python and am just trying to understand how its packages work. Presumably "eggs" are some sort of packaging mechanism, but what would be a quick overview of what role they play and maybe some information on why they're useful and how to create them?
Same concept as a `.jar` file in Java, it is a `.zip` file with some metadata files renamed `.egg`, for distributing code as bundles. [Specifically: The Internal Structure of Python Eggs](http://svn.python.org/projects/sandbox/trunk/setuptools/doc/formats.txt) > A "Python egg" is a logical structure embodying the rel...
Django Table with Million of rows
2,051,481
7
2010-01-12T18:47:30Z
2,051,499
8
2010-01-12T18:50:00Z
[ "python", "django", "django-models", "django-database" ]
I have a project with 2 applications ( books and reader ). Books application has a table with 4 milions of rows with this fields: ``` book_title = models.CharField(max_length=40) book_description = models.CharField(max_length=400) ``` To avoid to query the database with 4 milions of rows, I am thinking to divide i...
`ForeignKey` is implemented as `IntegerField` in the database, so you save little to nothing at the cost of crippling your model. **Edit:** And for pete's sake, keep it in one table and use indexes as appropriate.
Django Table with Million of rows
2,051,481
7
2010-01-12T18:47:30Z
2,052,058
10
2010-01-12T20:20:11Z
[ "python", "django", "django-models", "django-database" ]
I have a project with 2 applications ( books and reader ). Books application has a table with 4 milions of rows with this fields: ``` book_title = models.CharField(max_length=40) book_description = models.CharField(max_length=400) ``` To avoid to query the database with 4 milions of rows, I am thinking to divide i...
Like many have said, it's a bit premature to split your table up into smaller tables (horizontal partitioning or even sharding). Databases are made to handle tables of this size, so your performance problem is probably somewhere else. Indexes are the first step, it sounds like you've done this though. 4 million rows s...
Reverse Y-Axis in PyPlot
2,051,744
88
2010-01-12T19:31:47Z
2,052,203
9
2010-01-12T20:42:39Z
[ "python", "matplotlib" ]
I have a scatter plot graph with a bunch of random x, y coordinates. Currently the Y-Axis starts at 0 and goes up to the max value. I would like the Y-Axis to start at the max value and go up to 0. ``` points = [(10,5), (5,11), (24,13), (7,8)] x_arr = [] y_arr = [] for x,y in points: x_arr.append(x) y_arr....
Use [matplotlib.pyplot.axis()](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.axis) `axis([xmin, xmax, ymin, ymax])` So you could add something like this at the end: ``` plt.axis([min(x_arr), max(x_arr), max(y_arr), 0]) ``` Although you might want padding at each end so that the extreme poi...
Reverse Y-Axis in PyPlot
2,051,744
88
2010-01-12T19:31:47Z
2,052,799
22
2010-01-12T22:04:08Z
[ "python", "matplotlib" ]
I have a scatter plot graph with a bunch of random x, y coordinates. Currently the Y-Axis starts at 0 and goes up to the max value. I would like the Y-Axis to start at the max value and go up to 0. ``` points = [(10,5), (5,11), (24,13), (7,8)] x_arr = [] y_arr = [] for x,y in points: x_arr.append(x) y_arr....
[DisplacedAussie](http://stackoverflow.com/questions/2051744/pyplot-reverse-y-axis/2052203#2052203)'s answer is correct, but usually a shorter method is just to reverse the single axis in question: ``` plt.scatter(x_arr, y_arr) ax = plt.gca() ax.set_ylim(ax.get_ylim()[::-1]) ``` where the `gca()` function returns the...
Reverse Y-Axis in PyPlot
2,051,744
88
2010-01-12T19:31:47Z
8,280,500
204
2011-11-26T18:12:42Z
[ "python", "matplotlib" ]
I have a scatter plot graph with a bunch of random x, y coordinates. Currently the Y-Axis starts at 0 and goes up to the max value. I would like the Y-Axis to start at the max value and go up to 0. ``` points = [(10,5), (5,11), (24,13), (7,8)] x_arr = [] y_arr = [] for x,y in points: x_arr.append(x) y_arr....
There is a new API that makes this even simpler. ``` plt.gca().invert_xaxis() ``` and/or ``` plt.gca().invert_yaxis() ```
Reverse Y-Axis in PyPlot
2,051,744
88
2010-01-12T19:31:47Z
12,842,043
8
2012-10-11T14:34:13Z
[ "python", "matplotlib" ]
I have a scatter plot graph with a bunch of random x, y coordinates. Currently the Y-Axis starts at 0 and goes up to the max value. I would like the Y-Axis to start at the max value and go up to 0. ``` points = [(10,5), (5,11), (24,13), (7,8)] x_arr = [] y_arr = [] for x,y in points: x_arr.append(x) y_arr....
If you're in ipython in `pylab` mode, then ``` plt.gca().invert_yaxis() show() ``` the `show()` is required to make it update the current figure.
access to gnome configuration information using python
2,051,905
6
2010-01-12T19:56:43Z
2,051,921
10
2010-01-12T19:59:12Z
[ "python", "gnome" ]
Is there a standard way of accessing Gnome configuration information (i.e. `~/.gconf`) using Python? **Updated**: please provide a short example.
Python GConf, also check out packages like **python-gconf** and/or **gnome-python-gconf** in your distros package repo: > /usr/share/doc/python-gconf/examples/ Or **browse the svn** at <http://svn.gnome.org/viewvc/gnome-python/trunk/examples/gconf/> for the examples. On Fedora12 (my distro) it is called [gnome-pytho...
Efficient way to either create a list, or append to it if one already exists?
2,052,111
18
2010-01-12T20:27:13Z
2,052,206
22
2010-01-12T20:42:56Z
[ "python", "list" ]
I'm going through a whole bunch of tuples with a many-to-many correlation, and I want to make a dictionary where each b of (a,b) has a list of all the a's that correspond to a b. It seems awkward to test for a list at key b in the dictionary, then look for an a, then append a if it's not already there, every single tim...
See [the docs](http://docs.python.org/library/stdtypes.html#mapping-types-dict) for the `setdefault()` method: > setdefault(key[, default]) > If key is > in the dictionary, return its value. > If not, insert key with a value of > default and return default. default > defaults to None. You can use this as a single c...
Efficient way to either create a list, or append to it if one already exists?
2,052,111
18
2010-01-12T20:27:13Z
2,052,217
12
2010-01-12T20:44:52Z
[ "python", "list" ]
I'm going through a whole bunch of tuples with a many-to-many correlation, and I want to make a dictionary where each b of (a,b) has a list of all the a's that correspond to a b. It seems awkward to test for a list at key b in the dictionary, then look for an a, then append a if it's not already there, every single tim...
Assuming you're not really tied to lists, [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) and [set](http://docs.python.org/library/stdtypes.html#set) are quite handy. ``` import collections d = collections.defaultdict(set) for a, b in mappings: d[b].add(a) ``` If you *really...
How to throttle Django error emails
2,052,284
10
2010-01-12T20:53:55Z
8,997,843
7
2012-01-25T04:33:01Z
[ "python", "django", "error-handling", "error-reporting" ]
I use django error reporting via email. It is normally a very helpful feature, except that now we have 5 minutes of database downtime and I got 2000 emails. Is there any middleware that will help me throttle the number of emails django can send out per minute?
I limited emails to 10 per minute by doing the following. This uses a redis connection function unique to my install. I suggest modifying the incr\_counter function to suit your needs. To be safe, use a direct redis or memcache connection for this and not any django.cache wrappers. settings.py ``` LOGGING = { 've...
How to throttle Django error emails
2,052,284
10
2010-01-12T20:53:55Z
25,889,167
7
2014-09-17T11:20:46Z
[ "python", "django", "error-handling", "error-reporting" ]
I use django error reporting via email. It is normally a very helpful feature, except that now we have 5 minutes of database downtime and I got 2000 emails. Is there any middleware that will help me throttle the number of emails django can send out per minute?
Using Gattster's great answer as an example, I wrote a simple implementation based on django's built-in cache functions. ``` # -*- coding: utf-8 -*- from django.utils.log import AdminEmailHandler class ThrottledAdminEmailHandler(AdminEmailHandler): PERIOD_LENGTH_IN_SECONDS = 10 MAX_EMAILS_IN_PERIOD = 1 ...
Updating the wx.gauge without while-loop
2,052,369
4
2010-01-12T21:04:56Z
2,052,462
7
2010-01-12T21:16:20Z
[ "python", "wxpython" ]
Have been wondering about this for days now: I have a basic wxpython program like this: ``` from MyModule import * class Form(wx.Panel): def __init__(self, parent, id): self.gauge = wx.Gauge(...) ... def ButtonClick(self, event): proc = LongProcess() while (LongProcess): self.gauge.SetValue...
You can instantiate custom events from the non-GUI thread and wx.PostEvent them back to the GUI-thread. This is a thread-safe action. My use cases typically work like this: * Start worker thread - Custom event 'Starting Action' * Start processing * Post events back updating progress 'Line 435 of 15000 is parsed' * etc...
Manually raising (throwing) an exception in Python
2,052,390
797
2010-01-12T21:07:40Z
2,052,396
567
2010-01-12T21:08:45Z
[ "python", "exception", "exception-handling" ]
How can I raise an exception in Python so that it can later be caught via an `except` block?
> **DON'T DO THIS**. Raising a bare `Exception` is absolutely **not** the right thing to do; see [Aaron Hall's excellent answer](http://stackoverflow.com/a/24065533) instead. Can't get much more pythonic than this: ``` raise Exception("I know python!") ``` See [the raise statement docs](http://docs.python.org/refere...
Manually raising (throwing) an exception in Python
2,052,390
797
2010-01-12T21:07:40Z
24,065,533
785
2014-06-05T16:30:58Z
[ "python", "exception", "exception-handling" ]
How can I raise an exception in Python so that it can later be caught via an `except` block?
> # How do I manually throw/raise an exception in Python? [Use the most specific Exception constructor that semantically fits your issue](https://docs.python.org/3/library/exceptions.html#exception-hierarchy). Be specific in your message, e.g.: ``` raise ValueError('A very specific bad thing happened') ``` # Don't ...
Manually raising (throwing) an exception in Python
2,052,390
797
2010-01-12T21:07:40Z
30,317,038
15
2015-05-19T04:55:14Z
[ "python", "exception", "exception-handling" ]
How can I raise an exception in Python so that it can later be caught via an `except` block?
For the common case where you need to throw an exception in response to some unexpected conditions, and that you never intend to catch, but simply to fail fast to enable you to debug from there if it ever happens — the most logical one seems to be `AssertionError`: ``` if 0 < distance <= RADIUS: #Do something. e...
Python get all combinations of numbers
2,052,951
4
2010-01-12T22:31:52Z
2,052,981
20
2010-01-12T22:36:27Z
[ "python", "combinations" ]
I'm trying to display all possible combinations of a list of numbers, for example if I have 334 I want to get: ``` 3 3 4 3 4 3 4 3 3 ``` I need to be able to do this for any set of digits up to about 12 digits long. I'm sure its probably fairly simple using something like itertools.combinations but I can't quite get...
``` >>> lst = [3, 3, 4] >>> import itertools >>> set(itertools.permutations(lst)) {(3, 4, 3), (3, 3, 4), (4, 3, 3)} ```
Is the order of a Python dictionary guaranteed over iterations?
2,053,021
14
2010-01-12T22:42:01Z
2,053,036
31
2010-01-12T22:43:49Z
[ "python", "dictionary", "numpy", "scipy", "scientific-computing" ]
I'm currently implementing a complex microbial food-web in Python using [SciPy.integrate.ode](http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html). I need the ability to easily add species and reactions to the system, so I have to code up something quite general. My scheme looks something like ...
Yes, the same order is guaranteed if it is not modified. See the docs [here](https://docs.python.org/2/library/stdtypes.html#dict.items). **Edit:** Regarding if changing the value (but not adding/removing a key) will affect the order, this is what the comments in the C-source says: ``` /* CAUTION: PyDict_SetItem() ...
Is the order of a Python dictionary guaranteed over iterations?
2,053,021
14
2010-01-12T22:42:01Z
2,053,052
8
2010-01-12T22:49:02Z
[ "python", "dictionary", "numpy", "scipy", "scientific-computing" ]
I'm currently implementing a complex microbial food-web in Python using [SciPy.integrate.ode](http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html). I need the ability to easily add species and reactions to the system, so I have to code up something quite general. My scheme looks something like ...
Provided *no* modifications are made to the dictionary, the answer is yes. [See the docs here](https://docs.python.org/2/library/stdtypes.html#dict.items). However, dictionaries are unordered by nature in Python. In general, it's not the best practice to rely on dictionaries for sensitive sorted data. An example of a...
Git-diff to HTML
2,053,657
5
2010-01-13T00:56:03Z
2,058,104
8
2010-01-13T16:01:14Z
[ "python", "html", "git", "diff" ]
I'm looking for a way to produce HTML files from a git-diff output, preferably using python. I've been looking at <http://docs.python.org/library/difflib.html> without being able to figure out how to use the git-diff output as an input. Any clue? Many thanks
You could use the [pygments](http://pygments.org/docs/cmdline/) commandline script to get a syntax highligthed HTML output. Installation: ``` $ easy_install Pygments ``` Example: ``` $ git diff HEAD^1 > last.diff $ pygmentize -f html -O full,style=trac -l diff -o last.diff.html last.diff $ # mac only $ open last.d...
fastest way to compare strings in python
2,053,937
7
2010-01-13T02:11:49Z
2,053,954
15
2010-01-13T02:21:42Z
[ "python", "regex", "parsing" ]
I'm writing a script in Python that will allow the user to input a string, which will be a command that instructs the script to perform a specific action. For the sake of argument, I'll say my command list is: ``` lock read write request log ``` Now, I want the user to be able to enter the word "log" and it will pefo...
If you are accepting input from a user, then why are you worried about the speed of comparison? Even the slowest technique will be far faster than the user can perceive. Use the simplest most understandable code you can, and leave efficiency concerns for tight inner loops. ``` cmds = [ "lock", "read", "wri...
Getting the first elements per row in an array in Python?
2,054,416
11
2010-01-13T04:31:02Z
2,054,423
21
2010-01-13T04:32:18Z
[ "python", "tuples" ]
Let's say i have an array of Tuples, s, in the form of: ``` s = ((1, 23, 34),(2, 34, 44), (3, 444, 234)) ``` and i want to return another Tuple, t, consisting of the first element per row: ``` t = (1, 2, 3) ``` Which would be the most efficient method to do this? I could of course just iterate through s, but is the...
No. ``` t = tuple(x[0] for x in s) ```
Why can't Python handle true/false values as I expect?
2,055,029
31
2010-01-13T07:12:47Z
2,055,036
17
2010-01-13T07:14:20Z
[ "python", "python-2.x" ]
As part of answering another question, I wrote the following code whose behaviour seems bizarre at first glance: ``` print True # outputs true True = False; print True # outputs false True = True; print True # outputs false True = not True; print True # outputs true ``` Can anyone expl...
In 2.x, True and False are not keywords so it's possible to shadow the built-ins in this manner.
Why can't Python handle true/false values as I expect?
2,055,029
31
2010-01-13T07:12:47Z
2,055,060
41
2010-01-13T07:21:37Z
[ "python", "python-2.x" ]
As part of answering another question, I wrote the following code whose behaviour seems bizarre at first glance: ``` print True # outputs true True = False; print True # outputs false True = True; print True # outputs false True = not True; print True # outputs true ``` Can anyone expl...
Imagine this instead: ``` A = True B = False print A # true A = B; print A # false A = A; print A # false, because A is still false from before A = not A; print A # true, because A was false, so not A is true ``` The exact same thing is going on, but in your version it's confusing, because you don't ...
Why can't Python handle true/false values as I expect?
2,055,029
31
2010-01-13T07:12:47Z
2,055,081
10
2010-01-13T07:25:44Z
[ "python", "python-2.x" ]
As part of answering another question, I wrote the following code whose behaviour seems bizarre at first glance: ``` print True # outputs true True = False; print True # outputs false True = True; print True # outputs false True = not True; print True # outputs true ``` Can anyone expl...
You can check whether True/False is a keyword: ``` >>> import keyword >>> keyword.iskeyword('True') False ``` Since it's not (in my version), assigning True=False just means "True" is another "variable" name.
Why can't Python handle true/false values as I expect?
2,055,029
31
2010-01-13T07:12:47Z
2,055,144
72
2010-01-13T07:38:40Z
[ "python", "python-2.x" ]
As part of answering another question, I wrote the following code whose behaviour seems bizarre at first glance: ``` print True # outputs true True = False; print True # outputs false True = True; print True # outputs false True = not True; print True # outputs true ``` Can anyone expl...
Python has these two (among others) builtin objects. They are just objects; in the beginning, they don't have any names yet, but to know what we refer to, let's call them `0x600D` and `0xBAD`. Before starting to execute a Python (2.x) script, the name `True` gets bound to the object `0x600D`, and the name `False` gets...
python memory del list[:] vs list = []
2,055,107
3
2010-01-13T07:31:33Z
2,055,987
9
2010-01-13T10:37:41Z
[ "python", "memory" ]
In python I have noticed that if you do ``` mylist = [] for i in range(0,100000000): mylist.append('something here to take memory') mylist = [] ``` it would seem the second call ``` mylist = [] ``` would remove the reference and it would get collected but, as I watch them memory it does not. when I use ``` ...
How do you measure that? I've made a small test that does not confirm your results. Here is the source: ``` import meminfo, gc, commands page_size = int(commands.getoutput("getconf PAGESIZE")) def stat(message): s = meminfo.proc_stat() print "My memory usage %s: RSS: %dkb, VSIZE: %dkb" % ( message, ...
How to protect Python source code?
2,055,355
8
2010-01-13T08:30:09Z
2,055,395
11
2010-01-13T08:44:41Z
[ "python", "c", "compilation", "bytecode" ]
Is it possible to distribute only the bytecode version (.pyc file) of a Python script instead of the original .py file? My app embeds the Python interpreter and calls PyImport\_Import to load a script. How can I tell it to look for a .pyc file and import that?
Use the [freeze](http://wiki.python.org/moin/Freeze) tool, which is included in the Python source tree as [Tools/freeze](http://svn.python.org/view/python/trunk/Tools/freeze/). It converts Python byte code to C arrays; with a C compiler you can embed all your modules into a new program, which is then linked with the st...
python optimized mode
2,055,557
18
2010-01-13T09:21:00Z
2,083,834
22
2010-01-18T04:03:46Z
[ "python" ]
Python can run script in optimized mode (-O) that turns off debugs like assert and if I remember also remove docstrings. I have no seen it used really and maybe it is just artifact of the past times. Is it being used? What for? Why isn't this useless thing being removed in Python 3?
It saves a small amount of memory, and a small amount of disk space if you distribute any archive form containing only the `.pyo` files. (If you use `assert` a lot, and perhaps with complicated conditions, the savings can be not trivial and can extend to running time too). So, it's definitely not *useless* -- and of c...
python optimized mode
2,055,557
18
2010-01-13T09:21:00Z
2,167,639
30
2010-01-30T11:01:05Z
[ "python" ]
Python can run script in optimized mode (-O) that turns off debugs like assert and if I remember also remove docstrings. I have no seen it used really and maybe it is just artifact of the past times. Is it being used? What for? Why isn't this useless thing being removed in Python 3?
python -O does the following currently: * completely ignores asserts * sets the special builtin name `__debug__` to False (which by default is True) and when called as python -OO * removes docstrings from the code I don't know why everyone forgets to mention the `__debug__` issue; perhaps it is because I'm the only...
What is the best approach to change primary keys in an existing Django app?
2,055,784
25
2010-01-13T10:00:16Z
2,056,129
46
2010-01-13T11:11:43Z
[ "python", "django", "data-migration", "django-south" ]
I have an application which is in BETA mode. The model of this app has some classes with an explicit primary\_key. As a consequence Django use the fields and doesn't create an id automatically. ``` class Something(models.Model): name = models.CharField(max_length=64, primary_key=True) ``` I think that it was a ba...
Agreed, your model is probably wrong. The formal primary key should always be a surrogate key. Never anything else. [Strong words. Been database designer since the 1980's. Important lessoned learned is this: everything is changeable, even when the users swear on their mothers' graves that the value cannot be changed i...
What is the best approach to change primary keys in an existing Django app?
2,055,784
25
2010-01-13T10:00:16Z
10,250,962
9
2012-04-20T17:42:38Z
[ "python", "django", "data-migration", "django-south" ]
I have an application which is in BETA mode. The model of this app has some classes with an explicit primary\_key. As a consequence Django use the fields and doesn't create an id automatically. ``` class Something(models.Model): name = models.CharField(max_length=64, primary_key=True) ``` I think that it was a ba...
To change primary key with south you can use south.db.create\_primary\_key command in datamigration. To change your custom CharField pk to standard AutoField you should do: 1) create new field in your model ``` class MyModel(Model): id = models.AutoField(null=True) ``` 1.1) if you have a foreign key in some othe...
What is the Java Equivalent of Python's property()?
2,056,752
7
2010-01-13T13:03:49Z
2,056,781
7
2010-01-13T13:08:30Z
[ "java", "python", "properties" ]
I'm new to Java, and I'd like to create some class variables that are dynamically calculated when accessed, as you can do in Python by using the property() method. However, I'm not really sure how to describe this, so Googling shows me lots about the Java "Property" class, but this doesn't appear to be the same thing. ...
There's no such facility built into Java language. You have to write all the getters and setters explicitly by yourself. IDEs like Eclipse can generate this boilerplate code for you though. For example : ``` class Point{ private int x, y; public Point(int x, int y){ this.x = x; this.y = y; } public ...
python - os.makedirs don't understand ~ in my path?
2,057,045
37
2010-01-13T13:51:09Z
2,057,072
83
2010-01-13T13:55:50Z
[ "python", "path" ]
I have a little problem with ~ in my paths. This code example creates some dirs called "~/some\_dir", and do not understand that I wanted to create some\_dir in my home dir. ``` my_dir = "~/some_dir" if not os.path.exists(my_dir): os.makedirs(my_dir) ``` Note this is on a linux based system.
you need to expand the tilde manually: ``` my_dir = os.path.expanduser('~/some_dir') ```
python - os.makedirs don't understand ~ in my path?
2,057,045
37
2010-01-13T13:51:09Z
2,057,076
8
2010-01-13T13:57:01Z
[ "python", "path" ]
I have a little problem with ~ in my paths. This code example creates some dirs called "~/some\_dir", and do not understand that I wanted to create some\_dir in my home dir. ``` my_dir = "~/some_dir" if not os.path.exists(my_dir): os.makedirs(my_dir) ``` Note this is on a linux based system.
That's probably because Python is not Bash and doesn't follow same conventions. You may use this: ``` homedir = os.path.expanduser('~') ```
python - os.makedirs don't understand ~ in my path?
2,057,045
37
2010-01-13T13:51:09Z
2,057,111
25
2010-01-13T14:00:40Z
[ "python", "path" ]
I have a little problem with ~ in my paths. This code example creates some dirs called "~/some\_dir", and do not understand that I wanted to create some\_dir in my home dir. ``` my_dir = "~/some_dir" if not os.path.exists(my_dir): os.makedirs(my_dir) ``` Note this is on a linux based system.
The conversion of `~/some_dir` to `$HOME/some_dir` is called [tilde expansion](http://www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion) and is a common user interface feature. The file system does not know anything about it. In Python, this feature is implemented by [os.path.expanduser](http://docs.python...
Delete item in a list using a for-loop
2,057,419
4
2010-01-13T14:46:04Z
2,057,471
9
2010-01-13T14:51:23Z
[ "python", "list", "for-loop", "collections" ]
I have an array with subjects and every subject has connected time. I want to compare every subjects in the list. If there are two of the same subjects, I want to add the times of both subjects, and also want to delete the second subject information (subject-name and time). But If I delete the item, the list become sh...
Iterate backwards, if you can: ``` for x in range(subjectlength - 1, -1, -1): ``` and similarly for `y`.
Delete item in a list using a for-loop
2,057,419
4
2010-01-13T14:46:04Z
2,057,530
7
2010-01-13T14:57:29Z
[ "python", "list", "for-loop", "collections" ]
I have an array with subjects and every subject has connected time. I want to compare every subjects in the list. If there are two of the same subjects, I want to add the times of both subjects, and also want to delete the second subject information (subject-name and time). But If I delete the item, the list become sh...
The best practice is to make a new list of the entries to delete, and to delete them after walking the list: ``` to_del = [] subjectlength = 8 for x in range(subjectlength): for y in range(x): if subject[x] == subject[y]: #add time[x] = time[x] + time[y] to_del.append(y)...
Delete item in a list using a for-loop
2,057,419
4
2010-01-13T14:46:04Z
2,057,554
8
2010-01-13T14:59:47Z
[ "python", "list", "for-loop", "collections" ]
I have an array with subjects and every subject has connected time. I want to compare every subjects in the list. If there are two of the same subjects, I want to add the times of both subjects, and also want to delete the second subject information (subject-name and time). But If I delete the item, the list become sh...
If the elements of `subject` are hashable: ``` finalinfo = {} for s, t in zip(subject, time): finalinfo[s] = finalinfo.get(s, 0) + t ``` This will result in a dict with `subject: time` key-value pairs.
Worst practices in Django you have ever seen
2,058,532
24
2010-01-13T16:50:31Z
2,058,560
11
2010-01-13T16:54:17Z
[ "python", "django" ]
What are the worst mistakes made using Django framework, that you have noticed? Have you seen some real misuses, that maybe should go as warnings to the Django docs?
I tried to append items to my session without copying them out, appending the items, and then adding the list back to the session. This mistake is on a [NewbieMistakes](http://code.djangoproject.com/wiki/NewbieMistakes) page, so hopefully I'm in good company. This is the **correct** way to do it, in case anyone is cu...
Worst practices in Django you have ever seen
2,058,532
24
2010-01-13T16:50:31Z
2,058,590
11
2010-01-13T16:57:35Z
[ "python", "django" ]
What are the worst mistakes made using Django framework, that you have noticed? Have you seen some real misuses, that maybe should go as warnings to the Django docs?
Not splitting stuff up into multiple applications. It's not so much about reusability as it is about having a dozen models, and over 100 views in one app, it's damned unreadable. Plus I like to be able to scan my urls.py file easily to see where a URL points, when I have 100 URLs that gets harder.
Worst practices in Django you have ever seen
2,058,532
24
2010-01-13T16:50:31Z
2,058,929
9
2010-01-13T17:42:06Z
[ "python", "django" ]
What are the worst mistakes made using Django framework, that you have noticed? Have you seen some real misuses, that maybe should go as warnings to the Django docs?
I think the biggest problem is that people try to code as if this were Java/C: They try to create overly generic applications that need never be changed when future requirements change (which is necessary for Java/C because those apps aren't so easy to change/redesign). What results is a hideously complicated applicati...
Worst practices in Django you have ever seen
2,058,532
24
2010-01-13T16:50:31Z
2,060,303
23
2010-01-13T21:10:35Z
[ "python", "django" ]
What are the worst mistakes made using Django framework, that you have noticed? Have you seen some real misuses, that maybe should go as warnings to the Django docs?
Too much logic in views. I used to write views that would struggle to fit in 40 lines. Now I consider more than 2-3 indentation levels, 10 or so LOC or a handful of inline comments in a view to be code smells. The temptation is to write minimal models, figure out your url routing, then do everything else in the view....
How can I get the version defined in setup.py (setuptools) in my package?
2,058,802
82
2010-01-13T17:24:49Z
2,058,855
8
2010-01-13T17:30:37Z
[ "python", "setuptools" ]
How could I get the version defined in setup.py from my package (for `--version`, or other purposes)?
Your question is a little vague, but I think what you are asking is how to specify it. You need to define `__version__` like so: ``` __version__ = '1.4.4' ``` And then you can confirm that setup.py knows about the version you just specified: ``` % ./setup.py --version 1.4.4 ```
How can I get the version defined in setup.py (setuptools) in my package?
2,058,802
82
2010-01-13T17:24:49Z
2,058,872
8
2010-01-13T17:33:14Z
[ "python", "setuptools" ]
How could I get the version defined in setup.py from my package (for `--version`, or other purposes)?
The best technique is to define `__version__` in your product code, then import it into setup.py from there. This gives you a value you can read in your running module, and have only one place to define it. The values in setup.py are not installed, and setup.py doesn't stick around after installation. What I did (for...
How can I get the version defined in setup.py (setuptools) in my package?
2,058,802
82
2010-01-13T17:24:49Z
2,073,599
127
2010-01-15T17:38:25Z
[ "python", "setuptools" ]
How could I get the version defined in setup.py from my package (for `--version`, or other purposes)?
## Interrogate version string of already-installed distribution To retrieve the version from inside your package at runtime (what your question appears to actually be asking), you can use: ``` import pkg_resources # part of setuptools version = pkg_resources.require("MyProject")[0].version ``` ## Store version stri...
How can I get the version defined in setup.py (setuptools) in my package?
2,058,802
82
2010-01-13T17:24:49Z
24,517,154
10
2014-07-01T18:39:27Z
[ "python", "setuptools" ]
How could I get the version defined in setup.py from my package (for `--version`, or other purposes)?
# example study: `mymodule` Imagine this configuration: ``` setup.py mymodule/ / __init__.py / version.py / myclasses.py ``` Then imagine some usual scenario where you have dependencies and `setup.py` looks like: ``` setup(... install_requires=['dep1','dep2', ...] ...) ``` And an ex...
Python How to I check if last element has been reached in iterator tool chain?
2,058,894
14
2010-01-13T17:36:52Z
2,058,922
8
2010-01-13T17:40:35Z
[ "python" ]
``` for elt in itertools.chain.from_iterable(node): if elt is the last element: do statement ``` How do I achieve this
When the loop ends, the `elt` variable doesn't go out of scope, and still holds the last value given to it by the loop. So you could just put the code at the end of the loop and operate on the `elt` variable. It's not terribly pretty, but Python's scoping rules aren't pretty either. The only problem with this (thanks,...
Python How to I check if last element has been reached in iterator tool chain?
2,058,894
14
2010-01-13T17:36:52Z
2,058,973
16
2010-01-13T17:49:27Z
[ "python" ]
``` for elt in itertools.chain.from_iterable(node): if elt is the last element: do statement ``` How do I achieve this
You can do this by manually advancing the iterator in a while loop using `iter.next()`, then catching the `StopIteration` exception: ``` >>> from itertools import chain >>> it = chain([1,2,3],[4,5,6],[7,8,9]) >>> while True: ... try: ... elem = it.next() ... except StopIteration: ... print "Las...
How can I break up this long line in Python?
2,058,925
74
2010-01-13T17:41:07Z
2,058,937
20
2010-01-13T17:43:47Z
[ "python", "formatting", "code-formatting" ]
How would you go about formatting a long line such as this? I'd like to get it to no more than 80 characters wide: ``` logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title)) ``` Is this my best option? ``` url = "Skipping {0} because its thumbnai...
Consecutive string literals are joined by the compiler, and parenthesized expressions are considered to be a single line of code: ``` logger.info("Skipping {0} because it's thumbnail was " "already in our system as {1}.".format(line[indexes['url']], video.title)) ```
How can I break up this long line in Python?
2,058,925
74
2010-01-13T17:41:07Z
2,059,025
149
2010-01-13T17:59:25Z
[ "python", "formatting", "code-formatting" ]
How would you go about formatting a long line such as this? I'd like to get it to no more than 80 characters wide: ``` logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title)) ``` Is this my best option? ``` url = "Skipping {0} because its thumbnai...
That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another: ``` ("This is the first line of my text, " "which will be joined t...
Python If Statement with Multiple Conditions
2,059,111
12
2010-01-13T18:14:58Z
2,059,120
42
2010-01-13T18:16:18Z
[ "python", "syntax" ]
``` if (message.value[0] == "/" or message.value[0] == "\"): do stuff. ``` I'm sure it's a simple syntax error, but something is wrong with this if statement.
Escape the backslash: ``` if message.value[0] == "/" or message.value[0] == "\\": ``` From the [documentation](http://docs.python.org/reference/lexical_analysis.html#string-literals): > The backslash (\) character is used to > escape characters that otherwise have > a special meaning, such as newline, > backslash it...
Python If Statement with Multiple Conditions
2,059,111
12
2010-01-13T18:14:58Z
2,059,135
48
2010-01-13T18:18:11Z
[ "python", "syntax" ]
``` if (message.value[0] == "/" or message.value[0] == "\"): do stuff. ``` I'm sure it's a simple syntax error, but something is wrong with this if statement.
When you only need to check for equality, you can also simply use the [`in`](http://docs.python.org/3/reference/expressions.html#in) operator to do a membership test in a sequence of accepted elements: ``` if message.value[0] in ('/', '\\'): do_stuff() ```
BeautifulSoup HTML table parsing
2,059,328
17
2010-01-13T18:50:14Z
2,059,366
32
2010-01-13T18:56:45Z
[ "python", "table", "beautifulsoup", "mechanize", "html-parsing" ]
I am trying to parse information (html tables) from this site: <http://www.511virginia.org/RoadConditions.aspx?j=All&r=1> Currently I am using BeautifulSoup and the code I have looks like this ``` from mechanize import Browser from BeautifulSoup import BeautifulSoup mech = Browser() url = "http://www.511virginia.or...
``` start = cols[1].find('a').string ``` or simpler ``` start = cols[1].a.string ``` or better ``` start = str(cols[1].find(text=True)) ``` and ``` entry = [str(x) for x in cols.findAll(text=True)] ```
Python - temporarily modify the current process's environment
2,059,482
8
2010-01-13T19:13:32Z
2,059,494
18
2010-01-13T19:16:00Z
[ "environment-variables", "python" ]
I use the following code to temporarily modify environment variables. ``` @contextmanager def _setenv(**mapping): """``with`` context to temporarily modify the environment variables""" backup_values = {} backup_remove = set() for key, value in mapping.items(): if key in os.environ: ...
``` _environ = dict(os.environ) ... os.environ.clear() os.environ.update(_environ) ```
Using an index to recursively get all files in a directory really fast
2,059,912
2
2010-01-13T20:15:53Z
2,059,939
7
2010-01-13T20:20:40Z
[ "python", "indexing", "directory", "performance", "all-files" ]
**Attempt #2:** People don't seem to be understanding what I'm trying to do. Let me see if I can state it more clearly: 1) Reading a list of files is much faster than walking a directory. 2) So let's have a function that walks a directory and writes the resulting list to a file. Now, in the future, if we want to get...
Do not try to duplicate the work that the filesystem already does. You are not going to do better than it already does. Your scheme is flawed in many ways and it will not get you an order-of-magnitude improvement. Flaws and potential problems: You are always going to be working with a snapshot of the file system. Yo...