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
Remove all occurrences of a value from a Python list
1,157,106
167
2009-07-21T03:12:10Z
1,157,174
64
2009-07-21T03:33:13Z
[ "python", "list" ]
In Python `remove()` will remove the first occurrence of value in a list. How to remove all occurrences of a value from a list, without sorting the list? This is what I have in mind. ``` >>> x = [1, 2, 3, 4, 2, 2, 3] >>> def remove_values_from_list(the_list, val): while val in the_list: the_list....
You can use slice assignment if the original list must be modified, while still using an efficient list comprehension (or generator expression). ``` >>> x = [1, 2, 3, 4, 2, 2, 3] >>> x[:] = (value for value in x if value != 2) >>> x [1, 3, 4, 3] ```
Remove all occurrences of a value from a Python list
1,157,106
167
2009-07-21T03:12:10Z
26,419,313
9
2014-10-17T06:42:03Z
[ "python", "list" ]
In Python `remove()` will remove the first occurrence of value in a list. How to remove all occurrences of a value from a list, without sorting the list? This is what I have in mind. ``` >>> x = [1, 2, 3, 4, 2, 2, 3] >>> def remove_values_from_list(the_list, val): while val in the_list: the_list....
Repeating the solution of the first post in a more abstract way: ``` >>> x = [1, 2, 3, 4, 2, 2, 3] >>> while 2 in x: x.remove(2) >>> x [1, 3, 4, 3] ```
How to update an older C extension for Python 2.x to Python 3.x
1,157,134
2
2009-07-21T03:18:46Z
1,157,170
7
2009-07-21T03:31:25Z
[ "python", "c", "windows", "console" ]
I'm wanting to use an extension for Python that I found [here](http://effbot.org/zone/console-index.htm), but I'm using Python 3.1 and when I attempt to compile the C extension included in the package (\_wincon), it does not compile due to all the syntax errors. Unfortunately, it was written for 2.x versions of Python ...
I don't believe there is any magic bullet to make the C sources for a Python extension coded for some old-ish version of Python 2, into valid C sources for one coded for Python 3 -- it takes understanding of C and of how the C API has changed, and of what exactly the extension is doing in each part of its code. Believe...
Creating a board game simulator (Python?) (Pygame?)
1,157,245
14
2009-07-21T04:03:33Z
1,157,289
25
2009-07-21T04:18:01Z
[ "python", "pygame" ]
I've decided to start working on programming an old favorite of mine. I've never done a game before and also never done a large project in Python. The game is the old Avalon Hill game [Russian Campaign](http://www.boardgamegeek.com/boardgame/2808) I've been playing with PyGame a little bit and was wondering if there ...
Separate the "back-end" engine (which keeps track of board state, receives move orders from front-ends, generates random numbers to resolve battles, sends updates to front-ends, deals with saving and restoring specific games, ...) from "front-end" ones, which basically supply user interfaces for all of this. PyGame is...
get group id by group name (Python, Unix)
1,157,864
7
2009-07-21T08:05:05Z
1,157,958
14
2009-07-21T08:34:41Z
[ "python", "linux", "unix" ]
I want to use Python to get the group id to a corresponding group name. The routine must work for Unix-like OS (Linux and Mac OS X). This is what I found so far ``` >>> import grp >>> for g in grp.getgrall(): ... if g[0] == 'wurzel': ... print g[2] ```
If you read the [grp module documentation](http://docs.python.org/library/grp.html) you'll see that grp.getgrnam(groupname) will return one entry from the group database, which is a tuple-like object. You can either access the information by index or by attribute: ``` >>> import grp >>> groupinfo = grp.getgrnam('root'...
Implement touch using Python?
1,158,076
160
2009-07-21T09:05:11Z
1,158,096
23
2009-07-21T09:11:18Z
[ "python", "utility" ]
`touch` is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions. How would you implement it as a Python function? Try to be cross platform and complete. (Current Google results for "python touch file" are not ...
``` def touch(fname): if os.path.exists(fname): os.utime(fname, None) else: open(fname, 'a').close() ```
Implement touch using Python?
1,158,076
160
2009-07-21T09:05:11Z
1,160,227
159
2009-07-21T16:17:59Z
[ "python", "utility" ]
`touch` is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions. How would you implement it as a Python function? Try to be cross platform and complete. (Current Google results for "python touch file" are not ...
This tries to be a little more race-free than the other solutions. (The `with` keyword is new in Python 2.5.) ``` import os def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) ``` Roughly equivalent to this. ``` import os def touch(fname, times=None): fhandle = open(fname, 'a'...
Implement touch using Python?
1,158,076
160
2009-07-21T09:05:11Z
6,222,692
14
2011-06-03T03:31:28Z
[ "python", "utility" ]
`touch` is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions. How would you implement it as a Python function? Try to be cross platform and complete. (Current Google results for "python touch file" are not ...
Why not try this?: ``` def touch(fname): try: os.utime(fname, None) except: open(fname, 'a').close() ``` I believe this eliminates any race condition that matters. If the file does not exist then an exception will be thrown. The only possible race condition here is if the file is created befo...
Implement touch using Python?
1,158,076
160
2009-07-21T09:05:11Z
34,603,829
20
2016-01-05T03:45:06Z
[ "python", "utility" ]
`touch` is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions. How would you implement it as a Python function? Try to be cross platform and complete. (Current Google results for "python touch file" are not ...
Looks like this is new as of Python 3.4 - [`pathlib`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.touch). ``` from pathlib import Path Path('path/to/file.txt').touch() ``` This will create a `file.txt` at the path. -- > Path.touch(mode=0o777, exist\_ok=True) > > Create a file at this given path. If...
python - Importing a file that is a symbolic link
1,158,108
7
2009-07-21T09:15:35Z
1,158,116
9
2009-07-21T09:18:05Z
[ "python", "testing", "import" ]
If I have files x.py and y.py . And y.py is the link(symbolic or hard) of x.py . If I import both the modules in my script. Will it import it once or it assumes both are different files and import it twice. What it does exactly?
Python will import it twice. A link is a file system concept. To the Python interpreter, `x.py` and `y.py` are two different modules. ``` $ echo print \"importing \" + __file__ > x.py $ ln -s x.py y.py $ python -c "import x; import y" importing x.py importing y.py $ python -c "import x; import y" importing x.pyc impo...
python - Importing a file that is a symbolic link
1,158,108
7
2009-07-21T09:15:35Z
1,948,735
10
2009-12-22T19:54:49Z
[ "python", "testing", "import" ]
If I have files x.py and y.py . And y.py is the link(symbolic or hard) of x.py . If I import both the modules in my script. Will it import it once or it assumes both are different files and import it twice. What it does exactly?
You only have to be careful in the case where your script itself is a symbolic link, in which case the first entry of sys.path will be the directory containing the target of the link.
Merge sorted lists in python
1,158,128
10
2009-07-21T09:21:00Z
1,158,196
12
2009-07-21T09:38:03Z
[ "python", "arrays", "merge", "sorting" ]
I have a bunch of sorted lists of objects, and a comparison function ``` class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points < b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert ...
Python standard library offers a method for it: [`heapq.merge`](http://docs.python.org/library/heapq.html#heapq.merge). As the documentation says, it is very similar to using [itertools](http://docs.python.org/library/itertools.html#itertools.chain) (but with more limitations); if you cannot live with those limitatio...
How to implement a scripting language into a C application?
1,158,396
14
2009-07-21T10:32:13Z
1,158,418
17
2009-07-21T10:39:24Z
[ "python", "c", "scripting", "lua" ]
I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application). How does embedding and communication between my app and the scripts actuall...
Lua. It has a very small footprint, is rather fast, and I found it (subjectively) to have the most pleasant API to interact with C. If you want to touch the Lua objects from C - it's quite easy using the built-in APIs. If you want to touch C data from Lua - it's a bit more work, typically you'd need to make wrapper me...
How to implement a scripting language into a C application?
1,158,396
14
2009-07-21T10:32:13Z
1,158,502
7
2009-07-21T10:57:52Z
[ "python", "c", "scripting", "lua" ]
I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application). How does embedding and communication between my app and the scripts actuall...
Here's the document from the Python website for embedding Python 2.6... <http://docs.python.org/extending/embedding.html>
How to implement a scripting language into a C application?
1,158,396
14
2009-07-21T10:32:13Z
1,158,540
16
2009-07-21T11:06:47Z
[ "python", "c", "scripting", "lua" ]
I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application). How does embedding and communication between my app and the scripts actuall...
Some useful links: * [Embedding Python](http://docs.python.org/extending/embedding.html) * Embedding Lua: <http://www.lua.org/manual/5.1/manual.html#3>, <http://www.ibm.com/developerworks/opensource/library/l-embed-lua/index.html> * [Embedding Ruby](http://www.rubycentral.com/pickaxe/ext%5Fruby.html) * [Embedding PLT ...
How to implement a scripting language into a C application?
1,158,396
14
2009-07-21T10:32:13Z
1,162,177
8
2009-07-21T22:54:44Z
[ "python", "c", "scripting", "lua" ]
I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application). How does embedding and communication between my app and the scripts actuall...
Lua is totally optimized for exactly this sort of embedding. A good starting point is Roberto Ierusalimschy's book *Programming in Lua*; you can get the [previous edition free online](http://www.lua.org/pil/). **How does your script know about the properties of your C object?** Imagine for a moment your object is def...
How to Replace a column in a CSV file in Python?
1,159,524
5
2009-07-21T14:23:23Z
1,159,627
7
2009-07-21T14:40:21Z
[ "python", "csv" ]
I have 2 csv files. I need to replace a column in one file with a column from the other file but they have to stay sorted according to an ID column. Here's an example: file1: ``` ID, transect, 90mdist 1, a, 10, 2, b, 20, ...
The [CSV Module](http://docs.python.org/library/csv.html) in the Python Library is what you need here. It allows you to read and write CSV files, treating lines a tuples or lists of items. Just read in the file with the corrected values, store the in a dictionary keyed with the line's ID. Then read in the second fil...
Regex for keyboard mashing
1,159,690
5
2009-07-21T14:52:25Z
1,159,708
38
2009-07-21T14:55:51Z
[ "python", "regex", "fraud-prevention" ]
When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc. I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account. "Mot...
I would not do this - in my opinion these questions weaken the security, so as a user I always try to provide another semi-password as an answer - for you it would like mashed. Well, it is mashed, but that is exactly what I want to do. Btw. I am not sure about the fact, that you can query the answers. Since they overc...
Regex for keyboard mashing
1,159,690
5
2009-07-21T14:52:25Z
1,159,866
11
2009-07-21T15:16:30Z
[ "python", "regex", "fraud-prevention" ]
When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc. I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account. "Mot...
# The whole approach of security questions is quite flawed. I have always found **people put security answers weaker than the passwords they use**. Security questions are just one more link in a security chain -- the weaker link! IMO, a better way to go would be to **allow the user to request a new-password sent to...
models.py getting huge, what is the best way to break it up?
1,160,579
72
2009-07-21T17:27:11Z
1,160,607
49
2009-07-21T17:32:43Z
[ "python", "django", "django-models", "models" ]
Directions from my supervisor: "I want to avoid putting any logic in the `models.py`. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them." I feel like this is the wrong way to go. I feel that keeping logic out of...
Django is designed to let you build many small applications instead of one big application. Inside every large application are many small applications struggling to be free. If your `models.py` feels big, you're doing too much. Stop. Relax. Decompose. Find smaller, potentially reusable small application components, ...
models.py getting huge, what is the best way to break it up?
1,160,579
72
2009-07-21T17:27:11Z
1,160,735
81
2009-07-21T18:02:38Z
[ "python", "django", "django-models", "models" ]
Directions from my supervisor: "I want to avoid putting any logic in the `models.py`. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them." I feel like this is the wrong way to go. I feel that keeping logic out of...
It's natural for model classes to contain methods to operate on the model. If I have a Book model, with a method `book.get_noun_count()`, that's where it belongs--I don't want to have to write "`get_noun_count(book)`", unless the method actually intrinsically belongs with some other package. (It might--for example, if ...
How to use schemas in Django?
1,160,598
11
2009-07-21T17:30:53Z
1,628,855
18
2009-10-27T05:02:51Z
[ "python", "django", "postgresql", "django-models" ]
I whould like to use postgreSQL schemas with django, how can I do this?
I've been using: ``` db_table = '"schema"."tablename"' ``` in the past without realising that only work for read-only operation. When you try to add new record it would fail because the sequence would be something like "schema.tablename"\_column\_id\_seq. ``` db_table = 'schema\".\"tablename' ``` does work so far. ...
How to use schemas in Django?
1,160,598
11
2009-07-21T17:30:53Z
1,912,906
10
2009-12-16T07:18:15Z
[ "python", "django", "postgresql", "django-models" ]
I whould like to use postgreSQL schemas with django, how can I do this?
It's a bit more complicated than tricky escaping. Have a look at Ticket [#6148](http://code.djangoproject.com/ticket/6148) in Django for perhaps a solution or at least a patch. It makes some minor changes deep in the django.db core but it will hopefully be officially included in django. After that it's just a matter of...
How to use schemas in Django?
1,160,598
11
2009-07-21T17:30:53Z
18,391,525
7
2013-08-22T21:58:38Z
[ "python", "django", "postgresql", "django-models" ]
I whould like to use postgreSQL schemas with django, how can I do this?
As mentioned in the following ticket: <https://code.djangoproject.com/ticket/6148>, we could set `search_path` for the django user. One way to achieve this is to set `search_path` via `psql` client, like ``` ALTER USER my_user SET SEARCH_PATH TO path; ``` The other way is to modify the django app, so that if we rebu...
How to use schemas in Django?
1,160,598
11
2009-07-21T17:30:53Z
28,452,103
7
2015-02-11T10:35:48Z
[ "python", "django", "postgresql", "django-models" ]
I whould like to use postgreSQL schemas with django, how can I do this?
Maybe this will help. ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=your_schema' }, 'NAME': 'your_name', 'USER': 'your_user', 'PASSWORD': 'your_password', 'HOST': '127.0....
Django - last insert id
1,161,149
5
2009-07-21T19:12:17Z
1,161,217
7
2009-07-21T19:25:00Z
[ "python", "django" ]
I can't get the last insert id like I usually do and I'm not sure why. In my view: ``` comment = Comments( ...) comment.save() comment.id #returns None ``` In my Model: ``` class Comments(models.Model): id = models.IntegerField(primary_key=True) ``` Has anyone run into this problem before? Usually after I call...
Are you setting the value of the `id` field in the `comment = Comments( ...)` line? If not, why are you defining the field instead of just letting Django take care of the primary key with an AutoField? If you specify in IntegerField as a primary key as you're doing in the example Django won't automatically assign it a...
Python Notation?
1,161,658
2
2009-07-21T20:47:24Z
1,161,691
8
2009-07-21T20:55:07Z
[ "python", "naming-conventions", "notation" ]
I've just started using Python and I was thinking about which notation I should use. I've read the [PEP 8](http://www.python.org/dev/peps/pep-0008/) guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style). In C++ I use a modified version of the Hungar...
> (**Almost every Python programmer will say** it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me) FTFY. Seriously though, it will help you but confuse and annoy other Python programmers that try to read your code. This also isn'...
How can I get DNS records for a domain in python?
1,162,230
7
2009-07-21T23:11:15Z
1,162,308
9
2009-07-21T23:33:22Z
[ "python", "dns" ]
How do I get the DNS records for a zone in python? I'm looking for data similar to the output of `dig`.
Try the `dnspython` library: * <http://www.dnspython.org/> You can see some examples here: * <http://www.dnspython.org/examples.html>
What is the benefit of private name mangling in Python?
1,162,234
10
2009-07-21T23:11:31Z
1,162,248
22
2009-07-21T23:16:00Z
[ "python", "private-members", "name-mangling" ]
Python provides [private name mangling](http://docs.python.org/reference/expressions.html#atom-identifiers) for class methods and attributes. Are there any concrete cases where this feature is required, or is it just a carry over from Java and C++? **Please describe a use case where Python name mangling should be use...
It's partly to prevent accidental *internal* attribute access. Here's an example: In your code, which is a library: ``` class YourClass: def __init__(self): self.__thing = 1 # Your private member, not part of your API ``` In my code, in which I'm inheriting from your library class: ``` class M...
What is the benefit of private name mangling in Python?
1,162,234
10
2009-07-21T23:11:31Z
1,162,251
15
2009-07-21T23:16:38Z
[ "python", "private-members", "name-mangling" ]
Python provides [private name mangling](http://docs.python.org/reference/expressions.html#atom-identifiers) for class methods and attributes. Are there any concrete cases where this feature is required, or is it just a carry over from Java and C++? **Please describe a use case where Python name mangling should be use...
From [PEP 8](http://www.python.org/dev/peps/pep-0008/): > If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the cl...
Iterate over a string 2 (or n) characters at a time in Python
1,162,592
21
2009-07-22T01:24:53Z
1,162,624
12
2009-07-22T01:35:35Z
[ "python", "iteration" ]
Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like `"+c-R+D-E"` (there are a few extra letters). I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite. `...
Maybe this would be cleaner? ``` s = "+c-R+D-e" for i in xrange(0, len(s), 2): op, code = s[i:i+2] print op, code ``` You could perhaps write a generator to do what you want, maybe that would be more pythonic :)
Iterate over a string 2 (or n) characters at a time in Python
1,162,592
21
2009-07-22T01:24:53Z
1,162,636
32
2009-07-22T01:39:53Z
[ "python", "iteration" ]
Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like `"+c-R+D-E"` (there are a few extra letters). I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite. `...
Dunno about cleaner, but there's another alternative: ``` for (op, code) in zip(s[0::2], s[1::2]): print op, code ``` A no-copy version: ``` from itertools import izip, islice for (op, code) in izip(islice(s, 0, None, 2), islice(s, 1, None, 2)): print op, code ```
How would you model this database relationship?
1,162,877
2
2009-07-22T03:05:08Z
1,162,901
10
2009-07-22T03:14:48Z
[ "python", "database", "django", "database-design" ]
I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients. The application does need to know which one is which; further...
How about something like this: ``` class Patient(models.Model): primary_physician = models.ForeignKey('Physician', related_name='primary_patients') attending_physicial = models.ForeignKey('Physician', related_name='attending_patients') ``` This allows you to have two foreign keys to the same model; the `Physi...
How to detect the country and city of a user accessing your site?
1,163,136
5
2009-07-22T05:01:11Z
1,163,159
8
2009-07-22T05:07:50Z
[ "python", "web-applications" ]
How can you detect the country of origin of the users accessing your site? I'm using Google Analytics on my site and can see that I have users coming from different regions of the world. But within my application I would like to provide some additional customization based on the country and perhaps the city. Is it p...
Get the visitor's IP and check it with a [geolocation](http://en.wikipedia.org/wiki/Geolocation) web service (or purchase a geolocation database if you're keen to host that determination in-house).
How to detect the country and city of a user accessing your site?
1,163,136
5
2009-07-22T05:01:11Z
1,163,695
12
2009-07-22T07:49:14Z
[ "python", "web-applications" ]
How can you detect the country of origin of the users accessing your site? I'm using Google Analytics on my site and can see that I have users coming from different regions of the world. But within my application I would like to provide some additional customization based on the country and perhaps the city. Is it p...
Grab and gunzip <http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz>, install the GeoIP-Python package (python-geoip package if you're in Debian or Ubuntu, otherwise install <http://geolite.maxmind.com/download/geoip/api/python/GeoIP-Python-1.2.4.tar.gz>), and do: ``` import GeoIP gi = GeoIP.open("G...
Reading integers from binary file in Python
1,163,459
40
2009-07-22T06:48:39Z
1,163,508
68
2009-07-22T06:59:55Z
[ "python", "file", "binary", "integer" ]
I'm trying to read a [BMP](http://en.wikipedia.org/wiki/BMP_file_format) file in Python. I know the first two bytes indicate the BMP firm. The next 4 bytes are the file size. When I excecute: ``` fin = open("hi.bmp", "rb") firm = fin.read(2) file_size = int(fin.read(4)) ``` I get > ValueError: invalid literal for ...
The `read` method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in `struct` module: <http://docs.python.org/library/struct.html>. ``` import struct print(struct.unpack('i', fin.read(4))) ``` Note that `unpack` always returns a tuple, so `struct.unpack('...
Reading integers from binary file in Python
1,163,459
40
2009-07-22T06:48:39Z
11,713,266
22
2012-07-29T21:51:48Z
[ "python", "file", "binary", "integer" ]
I'm trying to read a [BMP](http://en.wikipedia.org/wiki/BMP_file_format) file in Python. I know the first two bytes indicate the BMP firm. The next 4 bytes are the file size. When I excecute: ``` fin = open("hi.bmp", "rb") firm = fin.read(2) file_size = int(fin.read(4)) ``` I get > ValueError: invalid literal for ...
An alternative method which does not make use of 'struct.unpack()' would be to use [NumPy](http://en.wikipedia.org/wiki/NumPy): ``` import numpy as np f = open("file.bin", "r") a = np.fromfile(f, dtype=np.uint32) ``` 'dtype' represents the datatype and can be int#, uint#, float#, complex# or a user defined type. See...
Python object creation
1,164,309
5
2009-07-22T10:19:34Z
1,164,319
13
2009-07-22T10:21:37Z
[ "python", "class", "object" ]
I am pretty new to Python world and trying to learn it. This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :) ``` class Car(): carName = "" #how can I define a n...
derived from object for [new-style class](http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes) use `__init__` to initialize the new instance, not `__self__` `__main__` is [helpful too](http://docs.python.org/library/%5F%5Fmain%5F%5F.html). ``` class Car(object): def __init__(self,inpu...
Image resizing with django?
1,164,930
11
2009-07-22T12:32:54Z
1,164,988
7
2009-07-22T12:43:47Z
[ "python", "django", "image", "python-imaging-library" ]
I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I hav...
If it's OK for you, there is a Django application ready, doing exactly what you want: <https://github.com/sorl/sorl-thumbnail>
Calculate difference in keys contained in two Python dictionaries
1,165,352
112
2009-07-22T13:43:13Z
1,165,398
14
2009-07-22T13:48:39Z
[ "python", "dictionary" ]
Suppose I have two Python dictionaries - `dictA` and `dictB`. I need to find out if there are any keys which are present in `dictB` but not in `dictA`. What is the fastest way to go about it? Should I convert the dictionary keys into a set and then go about? Interested in knowing your thoughts... --- Thanks for you...
not sure whether its "fast" or not, but normally, one can do this ``` dicta = {"a":1,"b":2,"c":3,"d":4} dictb = {"a":1,"d":2} for key in dicta.keys(): if not key in dictb: print key ```
Calculate difference in keys contained in two Python dictionaries
1,165,352
112
2009-07-22T13:43:13Z
1,165,429
14
2009-07-22T13:53:29Z
[ "python", "dictionary" ]
Suppose I have two Python dictionaries - `dictA` and `dictB`. I need to find out if there are any keys which are present in `dictB` but not in `dictA`. What is the fastest way to go about it? Should I convert the dictionary keys into a set and then go about? Interested in knowing your thoughts... --- Thanks for you...
As Alex Martelli wrote, if you simply want to check if any key in B is not in A, `any(True for k in dictB if k not in dictA)` would be the way to go. To find the keys that are missing: ``` diff = set(dictB)-set(dictA) #sets C:\Dokumente und Einstellungen\thc>python -m timeit -s "dictA = dict(zip(range(1000),rang...
Calculate difference in keys contained in two Python dictionaries
1,165,352
112
2009-07-22T13:43:13Z
1,165,552
176
2009-07-22T14:11:51Z
[ "python", "dictionary" ]
Suppose I have two Python dictionaries - `dictA` and `dictB`. I need to find out if there are any keys which are present in `dictB` but not in `dictA`. What is the fastest way to go about it? Should I convert the dictionary keys into a set and then go about? Interested in knowing your thoughts... --- Thanks for you...
You can use set operations on the keys: ``` diff = set(dictb.keys()) - set(dicta.keys()) ``` Here is a class to find all the possibilities: what was added, what was removed, which key-value pairs are the same, and which key-value pairs are changed. ``` class DictDiffer(object): """ Calculate the difference b...
Calculate difference in keys contained in two Python dictionaries
1,165,352
112
2009-07-22T13:43:13Z
1,166,569
12
2009-07-22T16:39:16Z
[ "python", "dictionary" ]
Suppose I have two Python dictionaries - `dictA` and `dictB`. I need to find out if there are any keys which are present in `dictB` but not in `dictA`. What is the fastest way to go about it? Should I convert the dictionary keys into a set and then go about? Interested in knowing your thoughts... --- Thanks for you...
If you really mean exactly what you say (that you only need to find out IF "there are any keys" in B and not in A, not WHICH ONES might those be if any), the fastest way should be: ``` if any(True for k in dictB if k not in dictA): ... ``` If you actually need to find out WHICH KEYS, if any, are in B and not in A, an...
Calculate difference in keys contained in two Python dictionaries
1,165,352
112
2009-07-22T13:43:13Z
26,079,022
23
2014-09-27T20:41:27Z
[ "python", "dictionary" ]
Suppose I have two Python dictionaries - `dictA` and `dictB`. I need to find out if there are any keys which are present in `dictB` but not in `dictA`. What is the fastest way to go about it? Should I convert the dictionary keys into a set and then go about? Interested in knowing your thoughts... --- Thanks for you...
In case you want the difference recursively, I have written a package for python: <https://github.com/seperman/deepdiff> ## Installation Install from PyPi: ``` pip install deepdiff ``` ## Example usage Importing ``` >>> from deepdiff import DeepDiff >>> from pprint import pprint >>> from __future__ import print_f...
Including current date in python logging file
1,165,856
2
2009-07-22T14:50:32Z
1,165,931
8
2009-07-22T14:59:47Z
[ "python", "logging" ]
I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name? Because I restart the process every morning the TimedRotatingFileHandler won't work. The project is larger, so I would be interested in keeping...
You can use the [TimedRotatingFileHandler](http://docs.python.org/2/library/logging.handlers.html#timedrotatingfilehandler). For example: ``` import logging import logging.handlers LOG_FILENAME = '/tmp/log' # Set up a specific logger with our desired output level log = logging.getLogger(__name__) log.setLevel(loggin...
How to strip decorators from a function in python
1,166,118
34
2009-07-22T15:29:41Z
1,166,200
23
2009-07-22T15:42:28Z
[ "python", "decorator" ]
Let's say I have the following: ``` def with_connection(f): def decorated(*args, **kwargs): f(get_connection(...), *args, **kwargs) return decorated @with_connection def spam(connection): # Do something ``` I want to test the `spam` function without going through the hassle of setting up a connec...
In the general case, you can't, because ``` @with_connection def spam(connection): # Do something ``` is equivalent to ``` def spam(connection): # Do something spam = with_connection(spam) ``` which means that the "original" spam might not even exist anymore. A (not too pretty) hack would be this: ``` def...
How to strip decorators from a function in python
1,166,118
34
2009-07-22T15:29:41Z
1,166,227
12
2009-07-22T15:45:22Z
[ "python", "decorator" ]
Let's say I have the following: ``` def with_connection(f): def decorated(*args, **kwargs): f(get_connection(...), *args, **kwargs) return decorated @with_connection def spam(connection): # Do something ``` I want to test the `spam` function without going through the hassle of setting up a connec...
Behold, FuglyHackThatWillWorkForYourExampleButICantPromiseAnythingElse: ``` orig_spam = spam.func_closure[0].cell_contents ``` **Edit**: For functions/methods decorated more than once and with more complicated decorators you can try using the following code. It relies on the fact, that decorated functions are \_\_na...
How to strip decorators from a function in python
1,166,118
34
2009-07-22T15:29:41Z
1,167,248
22
2009-07-22T18:31:07Z
[ "python", "decorator" ]
Let's say I have the following: ``` def with_connection(f): def decorated(*args, **kwargs): f(get_connection(...), *args, **kwargs) return decorated @with_connection def spam(connection): # Do something ``` I want to test the `spam` function without going through the hassle of setting up a connec...
balpha's solution can be made more generalizable with this meta-decorator: ``` def include_original(dec): def meta_decorator(f): decorated = dec(f) decorated._original = f return decorated return meta_decorator ``` Then you can decorate your decorators with @include\_original, and ever...
Python textwrap Library - How to Preserve Line Breaks?
1,166,317
8
2009-07-22T15:55:52Z
1,166,367
13
2009-07-22T16:05:14Z
[ "python", "newline", "textwrapping" ]
When using Python's textwrap library, how can I turn this: ``` short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` into this: ``` short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx ``` I tried: ``` w = textwrap....
try ``` w = textwrap.TextWrapper(width=90,break_long_words=False,replace_whitespace=False) ``` that seemed to fix the problem for me I worked that out from what I read [here](http://docs.python.org/library/textwrap.html#textwrap.TextWrapper) (I've never used textwrap before)
Python textwrap Library - How to Preserve Line Breaks?
1,166,317
8
2009-07-22T15:55:52Z
26,538,082
7
2014-10-23T21:51:52Z
[ "python", "newline", "textwrapping" ]
When using Python's textwrap library, how can I turn this: ``` short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` into this: ``` short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx ``` I tried: ``` w = textwrap....
``` body = '\n'.join(['\n'.join(textwrap.wrap(line, 90, break_long_words=False, replace_whitespace=False)) for line in body.splitlines() if line.strip() != '']) ```
Automatically determine the natural language of a website page given its URL
1,167,262
9
2009-07-22T18:33:46Z
1,167,633
8
2009-07-22T19:28:33Z
[ "python", "url", "website", "nlp" ]
I'm looking for a way to automatically determine the natural language used by a website page, given its URL. In Python, a function like: ``` def LanguageUsed (url): #stuff ``` Which returns a language specifier (e.g. 'en' for English, 'jp' for Japanese, etc...) Summary of Results: I have a reasonable solution w...
This is usually accomplished by using character n-gram models. You can find [here](http://alias-i.com/lingpipe/demos/tutorial/langid/read-me.html) a state of the art language identifier for Java. If you need some help converting it to Python, just ask. Hope it helps.
Python: access class property from string
1,167,398
65
2009-07-22T18:52:14Z
1,167,419
110
2009-07-22T18:55:55Z
[ "python", "syntax" ]
I have a class like the following: ``` class User: def __init__(self): self.data = [] self.other_data = [] def doSomething(self, source): // if source = 'other_data' how to access self.other_data ``` I want to pass a string for the source variable in `doSomething` and access the class...
`x = getattr(self, source)` will work just perfectly if `source` names ANY attribute of self, include the `other_data` in your example.
Python: access class property from string
1,167,398
65
2009-07-22T18:52:14Z
1,168,132
79
2009-07-22T20:45:36Z
[ "python", "syntax" ]
I have a class like the following: ``` class User: def __init__(self): self.data = [] self.other_data = [] def doSomething(self, source): // if source = 'other_data' how to access self.other_data ``` I want to pass a string for the source variable in `doSomething` and access the class...
A picture's worth a thousand words: ``` >>> class c: pass o = c() >>> setattr(o, "foo", "bar") >>> o.foo 'bar' >>> getattr(o, "foo") 'bar' ```
Executing code for a custom Django 404 page
1,167,434
5
2009-07-22T18:58:17Z
1,167,480
11
2009-07-22T19:05:11Z
[ "python", "django" ]
I am getting ready to deploy my first Django application and am hitting a bit of a roadblock. My base template relies on me passing in the session object so that it can read out the currently logged in user's name. This isn't a problem when I control the code that is calling a template. However, as part of getting thi...
You need to override the default view handler for the 404 error. Here is the documentation on how to create your own custom 404 view function: <http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views>
In Python, how do I indicate I'm overriding a method?
1,167,617
61
2009-07-22T19:26:48Z
1,167,664
9
2009-07-22T19:32:09Z
[ "python", "inheritance", "override", "self-documenting-code" ]
In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the...
Python ain't Java. There's of course no such thing really as compile-time checking. I think a comment in the docstring is plenty. This allows any user of your method to type `help(obj.method)` and see that the method is an override. You can also explicitly extend an interface with `class Foo(Interface)`, which will a...
In Python, how do I indicate I'm overriding a method?
1,167,617
61
2009-07-22T19:26:48Z
8,313,042
110
2011-11-29T15:07:19Z
[ "python", "inheritance", "override", "self-documenting-code" ]
In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the...
**UPDATE (23.05.2015): Based on this and fwc:s answer I created a pip installable package <https://github.com/mkorpela/overrides>** From time to time I end up here looking at this question. Mainly this happens after (again) seeing the same bug in our code base: Someone has forgotten some "interface" implementing class...
In Python, how do I indicate I'm overriding a method?
1,167,617
61
2009-07-22T19:26:48Z
14,631,397
19
2013-01-31T17:13:53Z
[ "python", "inheritance", "override", "self-documenting-code" ]
In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the...
Here's an implementation that doesn't require specification of the interface\_class name. ``` import inspect import re def overrides(method): # actually can't do this because a method is really just a function while inside a class def'n #assert(inspect.ismethod(method)) stack = inspect.stack() base...
Python scripts in /usr/bin
1,168,042
8
2009-07-22T20:27:38Z
1,168,048
12
2009-07-22T20:29:55Z
[ "python", "unix", "scripting" ]
I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension? For example, instead of running ``` python htswap.py args ``` from the directory where it currently is, I want to be able t...
The first line of the file should be ``` #!/usr/bin/env python ``` You should remove the `.py` extension, and make the file executable, using ``` chmod ugo+x htswap ``` **EDIT:** [Thomas](http://stackoverflow.com/users/14637/thomas) points out correctly that such scripts should be placed in `/usr/local/bin` rather ...
Python scripts in /usr/bin
1,168,042
8
2009-07-22T20:27:38Z
1,168,065
21
2009-07-22T20:32:43Z
[ "python", "unix", "scripting" ]
I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension? For example, instead of running ``` python htswap.py args ``` from the directory where it currently is, I want to be able t...
Simply strip off the `.py` extension by renaming the file. Then, you have to put the following line at the top of your file: ``` #!/usr/bin/env python ``` `env` is a little program that sets up the environment so that the right `python` interpreter is executed. You also have to make your file executable, with the co...
Boolean evaluation in a lambda
1,168,236
4
2009-07-22T21:03:36Z
1,168,311
9
2009-07-22T21:17:27Z
[ "python", "lambda" ]
Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda? ``` def isodd(number): if (number%2 == 0): return False else: return True ``` Elementary, yes. But I'm interested to know...
And if you don't really need a function you can replace it even without a lambda. :) ``` (number % 2 != 0) ``` by itself is an expression that evaluates to True or False. Or even plainer, ``` bool(number % 2) ``` which you can simplify like so: ``` if number % 2: print "Odd!" else: print "Even!" ``` But i...
IronPython vs. Python .NET
1,168,914
56
2009-07-23T00:06:00Z
1,168,933
49
2009-07-23T00:12:09Z
[ ".net", "python", "ironpython", "python.net" ]
I want to access some .NET assemblies written in C# from Python code. A little research showed I have two choices: * [IronPython](http://www.codeplex.com/IronPython) with .NET interface capability/support built-in * Python with the [Python .NET](http://pythonnet.sourceforge.net/) package What are the trade-offs betw...
If you want to mainly base your code on the .NET framework, I'd highly recommend IronPython vs Python.NET. IronPython is pretty much native .NET - so it just works great when integrating with other .NET langauges. Python.NET is good if you want to just integrate one or two components from .NET into a standard python a...
IronPython vs. Python .NET
1,168,914
56
2009-07-23T00:06:00Z
1,168,935
7
2009-07-23T00:12:16Z
[ ".net", "python", "ironpython", "python.net" ]
I want to access some .NET assemblies written in C# from Python code. A little research showed I have two choices: * [IronPython](http://www.codeplex.com/IronPython) with .NET interface capability/support built-in * Python with the [Python .NET](http://pythonnet.sourceforge.net/) package What are the trade-offs betw...
IronPython is ".NET-native" -- so it will be preferable if you want to fully integrate your Python code with .NET all the way; Python.NET works with Classic Python, so it lets you keep your Python code's "arm's length" away from .NET proper. (Note that with [this code](http://www.voidspace.org.uk/ironpython/cpython%5Fe...
IronPython vs. Python .NET
1,168,914
56
2009-07-23T00:06:00Z
1,168,957
23
2009-07-23T00:20:06Z
[ ".net", "python", "ironpython", "python.net" ]
I want to access some .NET assemblies written in C# from Python code. A little research showed I have two choices: * [IronPython](http://www.codeplex.com/IronPython) with .NET interface capability/support built-in * Python with the [Python .NET](http://pythonnet.sourceforge.net/) package What are the trade-offs betw...
While agreeing with the answers given by Reed Copsey and Alex Martelli, I'd like to point out one further difference - the Global Interpreter Lock (GIL). While IronPython doesn't have the limitations of the GIL, CPython does - so it would appear that for those applications where the GIL is a bottleneck, say in certain ...
Smart date interpretation
1,169,000
6
2009-07-23T00:36:47Z
1,169,014
8
2009-07-23T00:41:44Z
[ "python", "date-parsing" ]
I can't remember which application I was using, but I do recall it having really neat date parsing/interpretation. For example, you could type in 'two days ago' or 'tomorrow' and it would understand. Any libraries to suggest? Bonus points if usable from Python.
Perhaps you are thinking of PHP's `strtotime()` function, the [Swiss Army Knife of date parsing](http://brian.moonspot.net/2008/09/20/strtotime-the-php-date-swiss-army-knife/): > Man, what did I do before `strtotime()`. Oh, I know, I had a 482 line function to parse date formats and return timestamps. And I still coul...
Python OS X 10.5 development environment
1,169,025
4
2009-07-23T00:45:23Z
1,169,279
7
2009-07-23T02:32:01Z
[ "python", "google-app-engine", "osx", "development-environment" ]
I would like to try out the Google App Engine Python environment, which the docs say runs 2.5.2. As I use OS X Leopard, I have Python 2.5.1 installed, but would like the latest 2.5.x version installed (not 2.6 or 3.0). It seems the latest version is [2.5.4](http://www.python.org/download/releases/2.5.4/ "2.5.4") So, I...
You can install python on your Mac, and it won't mess with the default installation. However, I strongly recommend that you use [MacPorts](http://www.macports.org/) to install Python, since that will make it much easier for you to install Python libraries and packages further down the road. Additionally, if you try to ...
Adding Values From Tuples of Same Length
1,169,725
10
2009-07-23T05:15:44Z
1,169,760
10
2009-07-23T05:26:00Z
[ "python" ]
In a graphical program I'm writing using pygame I use a tuple representing a coordinate like this: (50, 50). Sometimes, I call a function which returns another tuple such as (3, -5), which represents the change in coordinate. What is the best way to add the change value to the coordinate value. It would be nice if I ...
List comprehension is probably more readable, but here's another way: ``` >>> a = (1,2) >>> b = (3,4) >>> tuple(map(sum,zip(a,b))) (4,6) ```
Adding Values From Tuples of Same Length
1,169,725
10
2009-07-23T05:15:44Z
1,169,769
13
2009-07-23T05:29:15Z
[ "python" ]
In a graphical program I'm writing using pygame I use a tuple representing a coordinate like this: (50, 50). Sometimes, I call a function which returns another tuple such as (3, -5), which represents the change in coordinate. What is the best way to add the change value to the coordinate value. It would be nice if I ...
Well, one way would be ``` coord = tuple(sum(x) for x in zip(coord, change)) ``` If you are doing a lot of math, you may want to investigate using [NumPy](http://numpy.scipy.org/), which has much more powerful array support and better performance.
Profiling Python Scripts running on Mod_wsgi
1,169,833
5
2009-07-23T05:52:07Z
1,169,914
9
2009-07-23T06:16:45Z
[ "python", "profiling", "wsgi" ]
How can I profile a python script running on mod\_wsgi on apache I would like to use cProfile but it seems it requires me to invoke a function manually. Is there a way to enable cProfile globally and have it keep on logging results.
You need to wrap you wsgi application function inside another function that just calls your function using cProfile and use that as the application. Or you can reuse existing WSGI middleware to do that for you, for example [repoze.profile](http://repoze.org/repoze%5Fcomponents.html) does pretty much what you seem to wa...
Python 2 CSV writer produces wrong line terminator on Windows
1,170,214
31
2009-07-23T07:34:11Z
1,170,297
53
2009-07-23T07:53:18Z
[ "python", "windows", "csv", "python-2.x", "line-endings" ]
According to the [its documentation](http://docs.python.org/library/csv.html#csv.Dialect.lineterminator) csv.writer should use '\r\n' as lineterminator by default. ``` import csv with open("test.csv", "w") as f: writer = csv.writer(f) rows = [(0,1,2,3,4), (-0,-1,-2,-3,-4), ("a","b","c",...
In Python 2.x, always open your file in **binary** mode, as documented. `csv` writes `\r\n` as you expected, but then the underlying Windows text file mechanism cuts in and changes that `\n` to `\r\n` ... total effect: `\r\r\n` From the [`csv.writer`](http://docs.python.org/library/csv.html#csv.writer) documentation: ...
Python 2 CSV writer produces wrong line terminator on Windows
1,170,214
31
2009-07-23T07:34:11Z
11,235,483
12
2012-06-27T22:08:27Z
[ "python", "windows", "csv", "python-2.x", "line-endings" ]
According to the [its documentation](http://docs.python.org/library/csv.html#csv.Dialect.lineterminator) csv.writer should use '\r\n' as lineterminator by default. ``` import csv with open("test.csv", "w") as f: writer = csv.writer(f) rows = [(0,1,2,3,4), (-0,-1,-2,-3,-4), ("a","b","c",...
Unfortunately, it's a bit different with the csv module for Python 3, but this code will work on both Python 2 and Python 3: ``` if sys.version_info >= (3,0,0): f = open(filename, 'w', newline='') else: f = open(filename, 'wb') ```
Python 2 CSV writer produces wrong line terminator on Windows
1,170,214
31
2009-07-23T07:34:11Z
31,418,457
11
2015-07-14T22:24:24Z
[ "python", "windows", "csv", "python-2.x", "line-endings" ]
According to the [its documentation](http://docs.python.org/library/csv.html#csv.Dialect.lineterminator) csv.writer should use '\r\n' as lineterminator by default. ``` import csv with open("test.csv", "w") as f: writer = csv.writer(f) rows = [(0,1,2,3,4), (-0,-1,-2,-3,-4), ("a","b","c",...
To change the line terminator in Python 2.7 csv writer use `writer = csv.writer(f, delimiter = '|', lineterminator='\n')` This is a much simpler way to change the default delimiter from \r\n.
How do I get urllib2 to log ALL transferred bytes
1,170,744
18
2009-07-23T09:56:43Z
1,181,585
11
2009-07-25T08:22:36Z
[ "python", "http", "logging", "urllib2" ]
I'm writing a web-app that uses several 3rd party web APIs, and I want to keep track of the low level request and responses for ad-hock analysis. So I'm looking for a recipe that will get Python's urllib2 to log all bytes transferred via HTTP. Maybe a sub-classed Handler?
Well, I've found how to setup the built-in debugging mechanism of the library: ``` import logging, urllib2, sys hh = urllib2.HTTPHandler() hsh = urllib2.HTTPSHandler() hh.set_http_debuglevel(1) hsh.set_http_debuglevel(1) opener = urllib2.build_opener(hh, hsh) logger = logging.getLogger() logger.addHandler(logging.Str...
How can I profile a SQLAlchemy powered application?
1,171,166
38
2009-07-23T11:33:39Z
1,175,677
59
2009-07-24T03:54:46Z
[ "python", "sqlalchemy", "profiler" ]
Does anyone have experience profiling a Python/SQLAlchemy app? And what are the best way to find bottlenecks and design flaws? We have a Python application where the database layer is handled by SQLAlchemy. The application uses a batch design, so a lot of database requests is done sequentially and in a limited timespa...
Sometimes just plain SQL logging (enabled via python's logging module or via the `echo=True` argument on `create_engine()`) can give you an idea how long things are taking. For example if you log something right after a SQL operation, you'd see something like this in your log: ``` 17:37:48,325 INFO [sqlalchemy.engine...
How can I profile a SQLAlchemy powered application?
1,171,166
38
2009-07-23T11:33:39Z
8,428,546
34
2011-12-08T09:06:54Z
[ "python", "sqlalchemy", "profiler" ]
Does anyone have experience profiling a Python/SQLAlchemy app? And what are the best way to find bottlenecks and design flaws? We have a Python application where the database layer is handled by SQLAlchemy. The application uses a batch design, so a lot of database requests is done sequentially and in a limited timespa...
There's an extremely useful profiling recipe on the [SQLAlchemy wiki](http://www.sqlalchemy.org/trac/wiki/UsageRecipes/Profiling) With a couple of minor modifications, ``` from sqlalchemy import event from sqlalchemy.engine import Engine import time import logging logging.basicConfig() logger = logging.getLogger("my...
How to increase connection pool size for Twisted?
1,171,519
3
2009-07-23T12:52:37Z
1,175,408
7
2009-07-24T01:38:48Z
[ "python", "connection-pooling", "twisted" ]
I'm using Twisted 8.1.0 as socket server engine. Reactor - epoll. Database server is MySQL 5.0.67. OS - Ubuntu Linux 8.10 32-bit in `/etc/mysql/my.cnf` : ``` max_connections = 1000 ``` in source code: ``` adbapi.ConnectionPool("MySQLdb", ..., use_unicode=True, charset='utf8', cp_min=3,...
As you suspect, this is probably a threading issue. `cp_max` sets an upper limit for the number of threads in the thread pool, however, your process is very likely running out of memory well below this limit, in your case around 200 threads. Because each thread has its own stack, the total memory being used by your pro...
How can I parse JSON in Google App Engine?
1,171,584
77
2009-07-23T13:09:20Z
1,171,730
111
2009-07-23T13:29:33Z
[ "python", "json", "google-app-engine" ]
I'd like to parse a JSON string into an object under Google App Engine (python). What do you recommend? Something to encode/stringify would be nice too. Is what you recommend built in, or a library that I have to include in my app? Is it secure? Thanks.
Consider using [Django's json lib](http://docs.djangoproject.com/en/dev/topics/serialization/), which is included with GAE. ``` from django.utils import simplejson as json # load the object from a string obj = json.loads( string ) ``` The link above has examples of Django's serializer, and here's the link for [simpl...
How can I parse JSON in Google App Engine?
1,171,584
77
2009-07-23T13:09:20Z
3,948,103
18
2010-10-16T07:58:42Z
[ "python", "json", "google-app-engine" ]
I'd like to parse a JSON string into an object under Google App Engine (python). What do you recommend? Something to encode/stringify would be nice too. Is what you recommend built in, or a library that I have to include in my app? Is it secure? Thanks.
Google App Engine now supports python 2.7. If using python 2.7, you can do the following: ``` import json structured_dictionary = json.loads(string_received) ```
Comparison of the multiprocessing module and pyro?
1,171,767
8
2009-07-23T13:34:07Z
1,955,757
14
2009-12-23T22:51:01Z
[ "python", "rpc", "multiprocessing", "pyro" ]
I use [pyro](http://pyro.sourceforge.net/) for basic management of parallel jobs on a compute cluster. I just moved to a cluster where I will be responsible for using all the cores on each compute node. (On previous clusters, each core has been a separate node.) The python [multiprocessing](http://docs.python.org/libra...
EDIT: I'm changing my answer so you avoid pain. multiprocessing is immature, the docs on BaseManager are **INCORRECT**, and if you're an object-oriented thinker that wants to create shared objects on the fly at run-time, **USE PYRO OR YOU WILL SERIOUSLY REGRET IT!** If you are just doing functional programming using a ...
Django-admin : How to display link to object info page instead of edit form , in records change list?
1,172,584
7
2009-07-23T15:26:41Z
1,172,814
19
2009-07-23T16:04:54Z
[ "python", "django", "django-admin", "admin" ]
I am customizing Django-admin for an application am working on . so far the customization is working file , added some views . but I am wondering how to change the records link in change\_list display to display an info page instead of change form ?! in this blog post :<http://www.theotherblog.com/Articles/2009/06/02/...
If I understand your question right you want to add your own link to the listing view, and you want that link to point to some info page you have created. To do that, create a function to return the link HTML in your Admin object. Then use that function in your list. Like this: ``` class ModelAdmin(admin.ModelAdmin):...
Django-admin : How to display link to object info page instead of edit form , in records change list?
1,172,584
7
2009-07-23T15:26:41Z
1,172,841
7
2009-07-23T16:08:31Z
[ "python", "django", "django-admin", "admin" ]
I am customizing Django-admin for an application am working on . so far the customization is working file , added some views . but I am wondering how to change the records link in change\_list display to display an info page instead of change form ?! in this blog post :<http://www.theotherblog.com/Articles/2009/06/02/...
Take a look at: <http://docs.djangoproject.com/en/dev/ref/contrib/admin/>, ModelAdmin.list\_display part, it says: A string representing an attribute on the model. This behaves almost the same as the callable, but self in this context is the model instance. Here's a full model example: ``` class Person(models.Model): ...
Connecting to APNS for iPhone Using Python
1,172,769
12
2009-07-23T15:57:29Z
1,254,027
8
2009-08-10T09:58:26Z
[ "iphone", "python", "ssl", "push-notification" ]
I'm trying to send push notifications to an iPhone using Python. I've exported my **certificate and private key** into a p12 file from keychain access and then converted it into pem file using the following command: ``` openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts ``` I'm using [APNSWrapper](http://code....
I recently did this using Django - <http://leecutsco.de/2009/07/14/push-on-the-iphone/> May be useful? It's making use of no extra libraries other than those included with Python already. Wouldn't take much to extract the send\_message() method out.
Randomness in Jython
1,173,520
8
2009-07-23T18:10:07Z
1,173,613
9
2009-07-23T18:26:53Z
[ "java", "python", "random", "jython" ]
When using (pseudo) random numbers in Jython, would it be more efficient to use the Python random module or Java's random class?
Python's version is much faster in a simple test on my Mac: ``` jython -m timeit -s "import random" "random.random()" ``` 1000000 loops, best of 3: 0.266 usec per loop vs ``` jython -m timeit -s "import java.util.Random; random=java.util.Random()" "random.nextDouble()" ``` 1000000 loops, best of 3: 1.65 usec per ...
What is a basic example of single inheritance using the super() keyword in Python?
1,173,992
22
2009-07-23T19:38:02Z
1,174,118
28
2009-07-23T19:57:25Z
[ "python", "inheritance", "constructor", "super" ]
Let's say I have the following classes set up: ``` class Foo: def __init__(self, frob, frotz): self.frobnicate = frob self.frotz = frotz class Bar: def __init__(self, frob, frizzle): self.frobnicate = frob self.frotz = 34 self.frazzle = frizzle ``` How can I...
Assuming you want class Bar to set the value 34 within its constructor, this would work: ``` class Foo(object): def __init__(self, frob, frotz): self.frobnicate = frob self.frotz = frotz class Bar(Foo): def __init__(self, frob, frizzle): super(Bar, self).__init__(frob, frizzle)...
What is a basic example of single inheritance using the super() keyword in Python?
1,173,992
22
2009-07-23T19:38:02Z
1,174,124
23
2009-07-23T19:58:31Z
[ "python", "inheritance", "constructor", "super" ]
Let's say I have the following classes set up: ``` class Foo: def __init__(self, frob, frotz): self.frobnicate = frob self.frotz = frotz class Bar: def __init__(self, frob, frizzle): self.frobnicate = frob self.frotz = 34 self.frazzle = frizzle ``` How can I...
In Python >=3.0, like this: ``` class Foo(): def __init__(self, frob, frotz) self.frobnicate = frob self.frotz = frotz class Bar(Foo): def __init__(self, frob, frizzle) super().__init__(frob, 34) self.frazzle = frizzle ``` Read more here: <http://docs.python.org/3.1/library/fu...
appengine: cached reference property?
1,174,075
2
2009-07-23T19:51:30Z
1,174,737
7
2009-07-23T21:57:58Z
[ "python", "database", "performance", "google-app-engine", "gae-datastore" ]
How can I cache a Reference Property in Google App Engine? For example, let's say I have the following models: ``` class Many(db.Model): few = db.ReferenceProperty(Few) class Few(db.Model): year = db.IntegerProperty() ``` Then I create many `Many`'s that point to only one `Few`: ``` one_few = Few.get_or_i...
The first time you dereference any reference property, the entity is fetched - even if you'd previously fetched the same entity associated with a different reference property. This involves a datastore get operation, which isn't as expensive as a query, but is still worth avoiding if you can. There's a good module tha...
How to efficiently calculate a running standard deviation?
1,174,984
53
2009-07-23T23:09:05Z
1,175,029
7
2009-07-23T23:21:19Z
[ "python", "perl", "statistics" ]
I have an array of lists of numbers, e.g.: ``` [0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) ``` What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all a...
[Statistics::Descriptive](http://search.cpan.org/perldoc/Statistics::Descriptive) is a very decent Perl module for these types of calculations: ``` #!/usr/bin/perl use strict; use warnings; use Statistics::Descriptive qw( :all ); my $data = [ [ 0.01, 0.01, 0.02, 0.04, 0.03 ], [ 0.00, 0.02, 0.02, 0.03, 0.02 ...
How to efficiently calculate a running standard deviation?
1,174,984
53
2009-07-23T23:09:05Z
1,175,084
61
2009-07-23T23:39:33Z
[ "python", "perl", "statistics" ]
I have an array of lists of numbers, e.g.: ``` [0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) ``` What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all a...
The basic answer is to accumulate the sum of both *x* (call it 'sum\_x1') and *x*2 (call it 'sum\_x2') as you go. The value of the standard deviation is then: ``` stdev = sqrt((sum_x2 / n) - (mean * mean)) ``` where ``` mean = sum_x / n ``` This is the sample standard deviation; you get the population standard devi...
How to efficiently calculate a running standard deviation?
1,174,984
53
2009-07-23T23:09:05Z
1,175,491
24
2009-07-24T02:32:58Z
[ "python", "perl", "statistics" ]
I have an array of lists of numbers, e.g.: ``` [0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) ``` What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all a...
Perhaps not what you were asking, but ... If you use a numpy array, it will do the work for you, efficiently: ``` from numpy import array nums = array(((0.01, 0.01, 0.02, 0.04, 0.03), (0.00, 0.02, 0.02, 0.03, 0.02), (0.01, 0.02, 0.02, 0.03, 0.02), (0.01, 0.00, 0.01, 0.05, 0.0...
How to efficiently calculate a running standard deviation?
1,174,984
53
2009-07-23T23:09:05Z
1,179,049
8
2009-07-24T17:34:54Z
[ "python", "perl", "statistics" ]
I have an array of lists of numbers, e.g.: ``` [0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) ``` What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all a...
Have a look at [PDL](http://search.cpan.org/dist/PDL/) (pronounced "piddle!"). This is the Perl Data Language which is designed for high precision mathematics and scientific computing. Here is an example using your figures.... ``` use strict; use warnings; use PDL; my $figs = pdl [ [0.01, 0.01, 0.02, 0.04, 0.03...
How to efficiently calculate a running standard deviation?
1,174,984
53
2009-07-23T23:09:05Z
1,348,615
71
2009-08-28T18:24:27Z
[ "python", "perl", "statistics" ]
I have an array of lists of numbers, e.g.: ``` [0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) ``` What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all a...
The answer is to use Welford's algorithm, which is very clearly defined after the "naive methods" in: * Wikipedia: [Algorithms for calculating variance](http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance) It's more numerically stable than either the two-pass or online simple sum of squares collectors su...
Elegant Python function to convert CamelCase to snake_case?
1,175,208
238
2009-07-24T00:22:02Z
1,176,023
365
2009-07-24T06:25:13Z
[ "python", "camelcasing" ]
Example: ``` >>> convert('CamelCase') 'camel_case' ```
This is pretty thorough: ``` def convert(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() ``` Works with all these (and doesn't harm already-un-cameled versions): ``` >>> convert('CamelCase') 'camel_case' >>> convert('CamelCamelCase') 'camel_came...
Elegant Python function to convert CamelCase to snake_case?
1,175,208
238
2009-07-24T00:22:02Z
12,867,228
56
2012-10-12T21:17:16Z
[ "python", "camelcasing" ]
Example: ``` >>> convert('CamelCase') 'camel_case' ```
I don't know why these are all so complicating. for most cases the simple expression `([A-Z]+)` will do the trick ``` >>> re.sub('([A-Z]+)', r'_\1','CamelCase').lower() '_camel_case' >>> re.sub('([A-Z]+)', r'_\1','camelCase').lower() 'camel_case' >>> re.sub('([A-Z]+)', r'_\1','camel2Case2').lower() 'camel2_case2' >...
Elegant Python function to convert CamelCase to snake_case?
1,175,208
238
2009-07-24T00:22:02Z
17,328,907
64
2013-06-26T19:34:34Z
[ "python", "camelcasing" ]
Example: ``` >>> convert('CamelCase') 'camel_case' ```
There's an [inflection library](https://pypi.python.org/pypi/inflection) in the package index that can handle these things for you. In this case, you'd be looking for [`inflection.underscore()`](http://inflection.readthedocs.org/en/latest/#inflection.underscore): ``` >>> inflection.underscore('CamelCase') 'camel_case'...
Elegant Python function to convert CamelCase to snake_case?
1,175,208
238
2009-07-24T00:22:02Z
19,940,888
14
2013-11-12T22:05:05Z
[ "python", "camelcasing" ]
Example: ``` >>> convert('CamelCase') 'camel_case' ```
Personally I am not sure how anything using regular expressions in python can be described as elegant. Most answers here are just doing "code golf" type RE tricks. Elegant coding is supposed to be easily understood. ``` def un_camel(x): final = '' for item in x: if item.isupper(): final += ...
Convert string to Python class object?
1,176,136
84
2009-07-24T07:01:23Z
1,176,179
60
2009-07-24T07:12:08Z
[ "python" ]
Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result: ``` class Foo: pass str_to_class("Foo") ==> <class __main_...
You could do something like: ``` globals()[class_name] ```
Convert string to Python class object?
1,176,136
84
2009-07-24T07:01:23Z
1,176,180
80
2009-07-24T07:13:10Z
[ "python" ]
Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result: ``` class Foo: pass str_to_class("Foo") ==> <class __main_...
This could work: ``` import sys def str_to_class(str): return getattr(sys.modules[__name__], str) ```
Convert string to Python class object?
1,176,136
84
2009-07-24T07:01:23Z
1,176,225
16
2009-07-24T07:25:27Z
[ "python" ]
Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result: ``` class Foo: pass str_to_class("Foo") ==> <class __main_...
``` import sys import types def str_to_class(field): try: identifier = getattr(sys.modules[__name__], field) except AttributeError: raise NameError("%s doesn't exist." % field) if isinstance(identifier, (types.ClassType, types.TypeType)): return identifier raise TypeError("%s is...
Convert string to Python class object?
1,176,136
84
2009-07-24T07:01:23Z
1,178,089
55
2009-07-24T14:32:24Z
[ "python" ]
Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result: ``` class Foo: pass str_to_class("Foo") ==> <class __main_...
This seems simplest. ``` >>> class Foo(object): ... pass ... >>> eval("Foo") <class '__main__.Foo'> ```
Convert string to Python class object?
1,176,136
84
2009-07-24T07:01:23Z
13,808,375
44
2012-12-10T20:08:18Z
[ "python" ]
Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result: ``` class Foo: pass str_to_class("Foo") ==> <class __main_...
You want the class "Baz", which lives in module "foo.bar". With python 2.7, you want to use importlib.import\_module(), as this will make transitioning to python 3 easier: ``` import importlib def class_for_name(module_name, class_name): # load the module, will raise ImportError if module cannot be loaded m =...
How to filter files (with known type) from os.walk?
1,176,441
17
2009-07-24T08:40:31Z
1,176,824
21
2009-07-24T10:23:41Z
[ "python" ]
I have list from `os.walk`. But I want to exclude some directories and files. I know how to do it with directories: ``` for root, dirs, files in os.walk('C:/My_files/test'): if "Update" in dirs: dirs.remove("Update") ``` But how can I do it with files, which type I know. because this doesn't work: ``` if...
``` files = [ fi for fi in files if not fi.endswith(".dat") ] ```