instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
Truncating floats in Python
I want to remove digits from a float to have a fixed number of digits after the dot, like: 1.923328437452 -> 1.923 I need to output as a string to another function, not print. Also I want to ignore the lost digits, not round them.
round(1.923328437452, 3) See Python's documentation on the standard types. You'll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to.
Random strings in Python 2.6 (Is this OK?)
I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to ''.join(random.choice(string.letters) for i in xrange(len)) It sucks if you want to generate long string. I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented. Somehow I got it to work, and it seems really fast. It generates a 50mil random string on my notebook in just about 3 seconds. def rand1(leng): nbits = leng * 6 + 1 bits = random.getrandbits(nbits) uc = u"%0x" % bits newlen = int(len(uc) / 2) * 2 # we have to make the string an even length ba = bytearray.fromhex(uc[:newlen]) return base64.urlsafe_b64encode(str(ba))[:leng] edit heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits. Still curious if there's a better way of doing this that's just as fast.
import os random_string = os.urandom(string_length)
Find free disk space in python on OS/X
I'm looking for the number of free bytes on my HD, but have trouble doing so on python. I've tried the following: import os stat = os.statvfs(path) print stat.f_bsize * stat.f_bavail But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true. What's the best way to get to this figure?
Try using f_frsize instead of f_bsize. >>> s = os.statvfs('/') >>> (s.f_bavail * s.f_frsize) / 1024 23836592L >>> os.system('df -k /') Filesystem 1024-blocks Used Available Capacity Mounted on /dev/disk0s2 116884912 92792320 23836592 80% /
How does a threading.Thread yield the rest of its quantum in Python?
I've got a thread that's polling a piece of hardware. while not hardware_is_ready(): pass process_data_from_hardware() But there are other threads (and processes!) that might have things to do. If so, I don't want to burn up cpu checking the hardware every other instruction. It's been a while since I've dealt with threading, and when I did it wasn't Python, but I believe most threading libraries have a yield function or something that allows a thread to tell the scheduler "Give the other threads a chance." while not hardware_is_ready(): threading.yield() # This function doesn't exist. process_data_from_hardware() But I can't find any reference to something like this in the threading documentation. Python does have a yield statement, but I'm pretty sure that's something else entirely (to do with generators). What's the correct thing to do here?
time.sleep(0) is sufficient to yield control -- no need to use a positive epsilon. Indeed, time.sleep(0) MEANS "yield to whatever other thread may be ready".
Python interface to PayPal - urllib.urlencode non-ASCII characters failing
I am trying to implement PayPal IPN functionality. The basic protocol is as such: The client is redirected from my site to PayPal's site to complete payment. He logs into his account, authorizes payment. PayPal calls a page on my server passing in details as POST. Details include a person's name, address, and payment info etc. I need to call a URL on PayPal's site internally from my processing page passing back all the params that were passed in abovem and an additional one called 'cmd' with a value of '_notify-validate'. When I try to urllib.urlencode the params which PayPal has sent to me, I get a: While calling send_response_to_paypal. Traceback (most recent call last): File "<snip>/account/paypal/views.py", line 108, in process_paypal_ipn verify_result = send_response_to_paypal(params) File "<snip>/account/paypal/views.py", line 41, in send_response_to_paypal params = urllib.urlencode(params) File "/usr/local/lib/python2.6/urllib.py", line 1261, in urlencode v = quote_plus(str(v)) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 9: ordinal not in range(128) I understand that urlencode does ASCII encoding, and in certain cases, a user's contact info can contain non-ASCII characters. This is understandable. My question is, how do I encode non-ASCII characters for POSTing to a URL using urllib2.urlopen(req) (or other method) Details: I read the params in PayPal's original request as follows (the GET is for testing): def read_ipn_params(request): if request.POST: params= request.POST.copy() if "ipn_auth" in request.GET: params["ipn_auth"]=request.GET["ipn_auth"] return params else: return request.GET.copy() The code I use for sending back the request to PayPal from the processing page is: def send_response_to_paypal(params): params['cmd']='_notify-validate' params = urllib.urlencode(params) req = urllib2.Request(PAYPAL_API_WEBSITE, params) req.add_header("Content-type", "application/x-www-form-urlencoded") response = urllib2.urlopen(req) status = response.read() if not status == "VERIFIED": logging.warn("PayPal cannot verify IPN responses: " + status) return False return True Obviously, the problem only arises if someone's name or address or other field used for the PayPal payment does not fall into the ASCII range.
Try converting the params dictionary to utf-8 first... urlencode seems to like that better than unicode: params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items())) Of course, this assumes your input is unicode. If your input is something other than unicode, you'll want to decode it to unicode first, then encode it: params['foo'] = my_raw_input.decode('iso-8859-1') params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items()))
How can I optimize this Python code to generate all words with word-distance 1?
Profiling shows this is the slowest segment of my code for a little word game I wrote: def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] Notes: distance() is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from word by exactly 1 letter. wordlist is pre-filtered to only have words containing the same number of letters as word so it's guaranteed that word1 and word2 have the same number of chars. I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated. for wordlist, take the 12dict word list using the "2+2lemma.txt" file Results: Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation) I tested with 2 sets of inputs which I'll call A and B Optimization1: iterate over indices of word1,2 ... from for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference to iterate on letter-pairs using zip(word1, word2) for x,y in zip (word1, word2): if x != y: difference += 1 return difference Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics) def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B Optimization3: Big winner here was to use izip instead of zip Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone! Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82 Building on that and incorporating izip instead of range, I ended up with this: def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88 Even more results! Trying Sumudu's suggestion that I generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist, instead of the is_neighbor function I ended up with this: def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact ( w for w in oneoff if w in wordlist ) I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with set-intersection on the letters: return set(oneoff) & set(wordlist) Bam! 3.74 -> 0.23 and 34.40 -> 2.25 This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation. If anyone is interested, I made blog post describing the program and describing the optimizations made including one that isn't mentioned here (because it's in a different section of code). The Great Debate: Ok, me and Unknown are having a big debate which you can read in the comments of his answer. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow this and this example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the 12dict word list using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries. from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "->"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) & set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) > 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score < g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this: def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) As for getting it to work as a C module I didn't get that far, but this is what I came up with: #include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &word1, &word2, &length)) return NULL; int i; int different = 0; for (i =0; i < length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } I profiled this using: python -m cProfile "Wordgame.py" And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.
If your wordlist is very long, might it be more efficient to generate all possible 1-letter-differences from 'word', then check which ones are in the list? I don't know any Python but there should be a suitable data structure for the wordlist allowing for log-time lookups. I suggest this because if your words are reasonable lengths (~10 letters), then you'll only be looking for 250 potential words, which is probably faster if your wordlist is larger than a few hundred words.
Check to see if python script is running
I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it? I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running. How can i check (using python) if my script is running?
A technique that is handy on a Linux system is using domain sockets: import socket import sys import time def get_lock(process_name): # Without holding a reference to our socket somewhere it gets garbage # collected when the function exits get_lock._lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) try: get_lock._lock_socket.bind('\0' + process_name) print 'I got the lock' except socket.error: print 'lock exists' sys.exit() get_lock('running_test') while True: time.sleep(3) It is atomic and avoids the problem of having lock files lying around if your process gets sent a SIGKILL You can read in the documentation for socket.close that sockets are automatically closed when garbage collected.
Turning on debug output for python 3 urllib
In python 2, it was possible to get debug output from urllib by doing import httplib import urllib httplib.HTTPConnection.debuglevel = 1 response = urllib.urlopen('http://example.com').read() However, in python 3 it looks like this has been moved to http.client.HTTPConnection.set_debuglevel(level) However, I'm using urllib not http.client directly. How can I set it up so that my http request display debugging information in this way? Here's what I"m using so far. What's the best way to proceed if I want to be able to get debug information? #Request Login page cookiejar = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar)) request = urllib.request.Request(options.uri) add_std_headers(request) response = opener.open(request) response_string = response.read().decode("utf8") # ...
You were right the first time. You can simply add the line http.client.HTTPConnection.debuglevel = 1 at the start of your file to turn on HTTP debugging application-wide. urllib.request still uses http.client. It seems that there's also a way to set the debuglevel for a single handler (by creating urllib.request.HTTPHandler(debuglevel=1) and building an opener with that), but on my installation of Python3 (3.0b3) it's not actually implemented. I imagine that's changed in more recent versions!
How do I return a CSV from a Pylons app?
I'm trying to return a CSV from an action in my webapp, and give the user a prompt to download the file or open it from a spreadsheet app. I can get the CSV to spit out onto the screen, but how do I change the type of the file so that the browser recognizes that this isn't supposed to be displayed as HTML? Can I use the csv module for this? import csv def results_csv(self): data = ['895', '898', '897'] return data
To tell the browser the type of content you're giving it, you need to set the Content-type header to 'text/csv'. In your Pylons function, the following should do the job: response.headers['Content-type'] = 'text/csv'
Which JSON module can I use in Python 2.5?
I would like to use Python's JSON module. It was only introduced in Python 2.6 and I'm stuck with 2.5 for now. Is the particular JSON module provided with Python 2.6 available as a separate module that can be used with 2.5?
You can use simplejson. As shown by the answer form pkoch you can use the following import statement to get a json library depending on the installed python version: try: import json except ImportError: import simplejson as json
Is Python the right hammer for this nail? (build script)
Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc. But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice? Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software. Edit: I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.
For a tool that is scripted with Python, I happen to think Paver is a more easily-managed and more flexible build automator than SCons. Unlike SCons, Paver is designed for the plethora of not-compiling-programs tasks that go along with managing and distributing a software project.
String formatting in Python version earlier than 2.6
When I run the following code in Python 2.5.2: for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) I get: Traceback (most recent call last): File "<pyshell#9>", line 2, in <module> print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attribute 'format' I don't understand the problem. From dir('hello') there is no format attribute. How can I solve this?
The str.format method was introduced in Python 3.0, and backported to Python 2.6 and later.
Built in python hash() function
Windows XP, Python 2.5: hash('http://stackoverflow.com') Result: 1934711907 Google App Engine (http://shell.appspot.com/): hash('http://stackoverflow.com') Result: -5768830964305142685 Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)?
As stated in the documentation, built-in hash() function is not designed for storing resulting hashes somewhere externally. It is used to provide object's hash value, to store them in dictionaries and so on. It's also implementation-specific (GAE uses a modified version of Python). Check out: >>> class Foo: ... pass ... >>> a = Foo() >>> b = Foo() >>> hash(a), hash(b) (-1210747828, -1210747892) As you can see, they are different, as hash() uses object's __hash__ method instead of 'normal' hashing algorithms, such as SHA. Given the above, the rational choice is to use the hashlib module.
Returning an object vs returning a tuple
I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object? In the first case, I get very low coupling, but then I will probably have to instantiate a Coord3D object with the obtained values anyway, although outside of the file class. In the second case, I will have the file class tightly coupled with the Coord3D class. Please note that I think there's not a huge difference between the two solutions, but I would like to read your answer and the reason behind it. Edit: to recap the answers I got until now, it looks like there's no clearcut choice. It has been said (appropriately) that python is not Java, and you don't need a specialized class for everything just because you need it by language architecture. In my case, however, I have the following conditions: I am working on a library, where the Coord3D object is used as is. Using it would increase the cohesiveness of my library, as the data types will be uniformly used. The Coord3D object has state and behavior. Indeed, the Coord3D object aggregate the coordinates and the units in a single entity. Operations among Coord3D objects will keep into account the potentially different units, and act accordingly. I can put centralize control code into the Coord3D class instantiation to refuse, for example, arrays of length 4, or non units. If I use a tuple, I cannot perform this check. Moreover, if a method accepts a Coord3D, is sort of guaranteed that it's well formed upfront (you could be bold and check for isinstance, or check the interface). A tuple can contain invalid data. Although python approach to error handling is done where the trouble happen, a class preventing me to have an xyz coordinate made out of three strings is somehow beneficial (correct me if wrong, please) On the other hand, using a tuple has the following advantages: Less occupation of resources, quite critical in case of huge Simpler design. More classes means more complex design. A tuple is a standard data type which is well understood and can be unpacked easily. A personalized class is not. Using a tuple, the XYZFile class is totally decoupled from the rest of the library (because it does not use the Coord3D object). This means that it can be reused totally as an independent entity. further comments very welcome!
Compromise solution: Instead of a class, make Coord3D a namedtuple and return that :-) Usage: Coord3D = namedtuple('Coord3D', 'x y z') def getCoordinate(index): # do stuff, creating variables x, y, z return Coord3D(x, y, z) The return value can be used exactly as a tuple, and has the same speed and memory properties, so you don't lose any genericity. But you can also access its values by name: if c is the result of getCoordinate(index), then you can work with c.x, c.y, etc, for increased readibility. (obviously this is a bit less useful if your Coord3D class needs other functionality too) [if you're not on python2.6, you can get namedtuples from the cookbook recipe]
Python list comprehension - access last created element?
Is it possible to access the previous element generated in a list comprehension. I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element and the key. The following loop would do. previous = initialization_value cipher = [] for element in message: previous = element ^ previous ^ key cipher.append(previous) I feel like it should be possible to turn this into a list comprehension but I am not exactly sure how to handle both the initial value or accessing the previous value generated. Is it possible and if so what would the comprehension be?
There isn't a good, Pythonic way to do this with a list comprehension. The best way to think about list comprehensions is as a replacement for map and filter. In other words, you'd use a list comprehension whenever you need to take a list and Use its elements as input for some expression (e.g. squaring the elements) Remove some of its elements based on some condition What these things have in common is that they each only look at a single list element at a time. This is a good rule of thumb; even if you could theoretically write the code you showed as a list comprehension, it would be awkward and unpythonic.
Google AppEngine: how to count a database's entries beyond 1000?
Duplicate of "how does one get a count of rows in a datastore model in google appengine?" I want to know how many users I have. Previously, I achieved this with the following code: users = UserStore.all() user_count = users.count() But now I have more than 1,000 users and this method continues to return 1,000. Is there an efficient programmatic way of knowing how many users I have?
It is indeed a duplicate and the other post describes how to theoretically do it, but I'd like to stress that you should really not be doing counts this way. The reason being that BigTable by its distributed nature is really bad for aggregates. What you probably want to do is add a transactional counter to that entity, and if there are lots of transactions a sharded counter. See: http://code.google.com/appengine/articles/sharding_counters.html UPDATE: Since 1.3.1 cursors make stuff like this a lot easier: http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html#Query_Cursors
Can't subtract offset-naive and offset-aware datetimes
I have a timezone aware timestamptz field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age. The problem I'm having is that both datetime.datetime.now() and datetime.datetime.utcnow() seem to return timezone unaware timestamps, which results in me getting this error: TypeError: can't subtract offset-naive and offset-aware datetimes Is there a way to avoid this (preferably without a third-party module being used). EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using: NOW() AT TIME ZONE 'UTC' That way all my timestamps are UTC by default (even though it's more annoying to do this). Hopefully I can eventually find a fix for this.
have you tried to remove the timezone awareness? from http://pytz.sourceforge.net/ naive = dt.replace(tzinfo=None) may have to add time zone conversion as well.
Python "protected" attributes
How do I access a private attribute of a parent class from a subclass (without making it public)?
My understanding of Python convention is _member is protected __member is private Options for if you control the parent class Make it protected instead of private since that seems like what you really want Use a getter (@property def _protected_access_to_member...) to limit the protected access If you don't control it Undo the name mangling. If you dir(object) you will see names something like _Class__member which is what Python does to leading __ to "make it private". There isn't truly private in python. This is probably considered evil.
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read. I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability? Has anyone seen a pretty-printing algorithm that does this already? In Python would be even better.
You can try sqlparse. It's a Python module that provides simple SQL formatting. A online demo is available here.
All combinations of a list of lists
I'm basically looking for a python version of Combination of List<List<int>> Given a list of lists, I need a new list that gives all the possible combinations of items between the lists. [[1,2,3],[4,5,6],[7,8,9,10]] -> [[1,4,7],[1,4,8],...,[3,6,10]] The number of lists is unknown, so I need something that works for all cases. Bonus points for elegance!
you need itertools.product: >>> import itertools >>> a = [[1,2,3],[4,5,6],[7,8,9,10]] >>> list(itertools.product(*a)) [(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]
Getting name of windows computer running python script?
Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script. How would I get that computer name in the python script? Let's say the script was running on a computer named DARK-TOWER, I'd like to write something like this: >>> python.library.getComputerName() 'DARK-TOWER' Is there a standard or third party library I can use?
It turns out there are three options (including the two already answered earlier): >>> import platform >>> import socket >>> import os >>> platform.node() 'DARK-TOWER' >>> socket.gethostname() 'DARK-TOWER' >>> os.environ['COMPUTERNAME'] 'DARK-TOWER'
How to get all of the immediate subdirectories in Python
I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). I'm getting bogged down by trying to get the list of subdirectories.
import os def get_immediate_subdirectories(a_dir): return [name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name))]
Django equivalent of PHP's form value array/associative array
In PHP, I would do this to get name as an array. <input type"text" name="name[]" /> <input type"text" name="name[]" /> Or if I wanted to get name as an associative array: <input type"text" name="name[first]" /> <input type"text" name="name[last]" /> What is the Django equivalent for such things?
Check out the QueryDict documentation, particularly the usage of QueryDict.getlist(key). Since request.POST and request.GET in the view are instances of QueryDict, you could do this: <form action='/my/path/' method='POST'> <input type='text' name='hi' value='heya1'> <input type='text' name='hi' value='heya2'> <input type='submit' value='Go'> </form> Then something like this: def mypath(request): if request.method == 'POST': greetings = request.POST.getlist('hi') # will be ['heya1','heya2']
How to put timedelta in django model?
With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object! Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str version of the object...
Since Django 1.8 you can use DurationField.
Changing user agent on urllib2.urlopen
How can I download a webpage with a user agent other than the default one on urllib2.urlopen?
I answered a similar question a couple weeks ago. There is example code in that question, but basically you can do something like this: (Note the capitalization of User-Agent as of RFC 2616, section 14.43.) opener = urllib2.build_opener() opener.addheaders = [('User-Agent', 'Mozilla/5.0')] response = opener.open('http://www.stackoverflow.com')
`final` keyword equivalent for variables in Python?
I couldn't find documentation on an equivalent of Java's final in Python, is there such a thing? I'm creating a snapshot of an object (used for restoration if anything fails); once this backup variable is assigned, it should not be modified -- a final-like feature in Python would be nice for this.
There is no ``final'' equivalent in Python. But, to create read-only fields of class instances, you can use the property function. Edit: perhaps you want something like this: class WriteOnceReadWhenever: def __setattr__(self, attr, value): if hasattr(self, attr): raise Exception("Attempting to alter read-only value") self.__dict__[attr] = value
Getting realtime output using subprocess
I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation. This requires me to be able to see each line of output from the wrapped program as soon as it is output. I figured that I'd just execute the program using subprocess.Popen, use stdout=PIPE, then read each line as it came in and act on it accordingly. However, when I ran the following code, the output appeared to be buffered somewhere, causing it to appear in two chunks, lines 1 through 332, then 333 through 439 (the last line of output) from subprocess import Popen, PIPE, STDOUT p = Popen('svnadmin verify /var/svn/repos/config', stdout = PIPE, stderr = STDOUT, shell = True) for line in p.stdout: print line.replace('\n', '') After looking at the documentation on subprocess a little, I discovered the bufsize parameter to Popen, so I tried setting bufsize to 1 (buffer each line) and 0 (no buffer), but neither value seemed to change the way the lines were being delivered. At this point I was starting to grasp for straws, so I wrote the following output loop: while True: try: print p.stdout.next().replace('\n', '') except StopIteration: break but got the same result. Is it possible to get 'realtime' program output of a program executed using subprocess? Is there some other option in Python that is forward-compatible (not exec*)?
I tried this, and for some reason while the code for line in p.stdout: ... buffers aggressively, the variant while True: line = p.stdout.readline() if not line: break ... does not. Apparently this is a known bug: http://bugs.python.org/issue3907
Passing functions with arguments to another function in Python?
Is it possible to pass functions with arguments to another function in Python? Say for something like: def Perform ( function ) : function but the functions to be passed will be like: Action1() Action2(p) Action3(p,r)
Do you mean this? def perform( fun, *args ): fun( *args ) def action1( args ): something def action2( args ): something perform( action1 ) perform( action2, p ) perform( action3, p, r )
Best way to convert a Unicode URL to ASCII (UTF-8 percent-escaped) in Python?
I'm wondering what's the best way -- or if there's a simple way with the standard library -- to convert a URL with Unicode chars in the domain name and path to the equivalent ASCII URL, encoded with domain as IDNA and the path %-encoded, as per RFC 3986. I get from the user a URL in UTF-8. So if they've typed in http://➡.ws/♥ I get 'http://\xe2\x9e\xa1.ws/\xe2\x99\xa5' in Python. And what I want out is the ASCII version: 'http://xn--hgi.ws/%E2%99%A5'. What I do at the moment is split the URL up into parts via a regex, and then manually IDNA-encode the domain, and separately encode the path and query string with different urllib.quote() calls. # url is UTF-8 here, eg: url = u'http://➡.ws/㉌'.encode('utf-8') match = re.match(r'([a-z]{3,5})://(.+\.[a-z0-9]{1,6})' r'(:\d{1,5})?(/.*?)(\?.*)?$', url, flags=re.I) if not match: raise BadURLException(url) protocol, domain, port, path, query = match.groups() try: domain = unicode(domain, 'utf-8') except UnicodeDecodeError: return '' # bad UTF-8 chars in domain domain = domain.encode('idna') if port is None: port = '' path = urllib.quote(path) if query is None: query = '' else: query = urllib.quote(query, safe='=&?/') url = protocol + '://' + domain + port + path + query # url is ASCII here, eg: url = 'http://xn--hgi.ws/%E3%89%8C' Is this correct? Any better suggestions? Is there a simple standard-library function to do this?
Code: import urlparse, urllib def fixurl(url): # turn string into unicode if not isinstance(url,unicode): url = url.decode('utf8') # parse it parsed = urlparse.urlsplit(url) # divide the netloc further userpass,at,hostport = parsed.netloc.rpartition('@') user,colon1,pass_ = userpass.partition(':') host,colon2,port = hostport.partition(':') # encode each component scheme = parsed.scheme.encode('utf8') user = urllib.quote(user.encode('utf8')) colon1 = colon1.encode('utf8') pass_ = urllib.quote(pass_.encode('utf8')) at = at.encode('utf8') host = host.encode('idna') colon2 = colon2.encode('utf8') port = port.encode('utf8') path = '/'.join( # could be encoded slashes! urllib.quote(urllib.unquote(pce).encode('utf8'),'') for pce in parsed.path.split('/') ) query = urllib.quote(urllib.unquote(parsed.query).encode('utf8'),'=&?/') fragment = urllib.quote(urllib.unquote(parsed.fragment).encode('utf8')) # put it back together netloc = ''.join((user,colon1,pass_,at,host,colon2,port)) return urlparse.urlunsplit((scheme,netloc,path,query,fragment)) print fixurl('http://\xe2\x9e\xa1.ws/\xe2\x99\xa5') print fixurl('http://\xe2\x9e\xa1.ws/\xe2\x99\xa5/%2F') print fixurl(u'http://Åsa:abc123@➡.ws:81/admin') print fixurl(u'http://➡.ws/admin') Output: http://xn--hgi.ws/%E2%99%A5 http://xn--hgi.ws/%E2%99%A5/%2F http://%C3%85sa:abc123@xn--hgi.ws:81/admin http://xn--hgi.ws/admin Read more: urllib.quote() urlparse.urlparse() urlparse.urlunparse() urlparse.urlsplit() urlparse.urlunsplit() Edits: Fixed the case of already quoted characters in the string. Changed urlparse/urlunparse to urlsplit/urlunsplit. Don't encode user and port information with the hostname. (Thanks Jehiah) When "@" is missing, don't treat the host/port as user/pass! (Thanks hupf)
Tool to determine what lowest version of Python required?
Is there something similar to Pylint, that will look at a Python script (or run it), and determine which version of Python each line (or function) requires? For example, theoretical usage: $ magic_tool <EOF with something: pass EOF 1: 'with' statement requires Python 2.6 or greater $ magic_tool <EOF class Something: @classmethod def blah(cls): pass EOF 2: classmethod requires Python 2.2 or greater $ magic_tool <EOF print """Test """ EOF 1: Triple-quote requires Python 1.5 of later Is such a thing possible? I suppose the simplest way would be to have all Python versions on disc, run the script with each one and see what errors occur..
Inspired by this excellent question, I recently put together a script that tries to do this. You can find it on github at pyqver. It's reasonably complete but there are some aspects that are not yet handled (as mentioned in the README file). Feel free to fork and improve it!
How to use subprocess when multiple arguments contain spaces?
I'm working on a wrapper script that will exercise a vmware executable, allowing for the automation of virtual machine startup/shutdown/register/deregister actions. I'm trying to use subprocess to handle invoking the executable, but the spaces in the executables path and in parameters of the executable are not being handled correctly by subprocess. Below is a code fragment: vmrun_cmd = r"c:/Program Files/VMware/VMware Server/vmware-cmd.bat" def vm_start(target_vm): list_arg = "start" list_arg2 = "hard" if vm_list(target_vm): p = Popen([vmrun_cmd, target_vm, list_arg, list_arg2], stdout=PIPE).communicate()[0] print p else: vm_register(target_vm) vm_start(target_vm) def vm_list2(target_vm): list_arg = "-l" p = Popen([vmrun_cmd, list_arg], stdout=PIPE).communicate()[0] for line in p.split('\n'): print line If I call the vm_list2 function, I get the following output: $ ./vmware_control.py --list C:\Virtual Machines\QAW2K3Server\Windows Server 2003 Standard Edition.vmx C:\Virtual Machines\ubunturouter\Ubuntu.vmx C:\Virtual Machines\vacc\vacc.vmx C:\Virtual Machines\EdgeAS-4.4.x\Other Linux 2.4.x kernel.vmx C:\Virtual Machines\UbuntuServer1\Ubuntu.vmx C:\Virtual Machines\Other Linux 2.4.x kernel\Other Linux 2.4.x kernel.vmx C:\Virtual Machines\QAClient\Windows XP Professional.vmx If I call the vm_start function, which requires a path-to-vm parameter, I get the following output: $ ./vmware_control.py --start "C:\Virtual Machines\ubunturouter\Ubuntu.vmx" 'c:\Program' is not recognized as an internal or external command, operable program or batch file. Apparently, the presence of a second parameter with embedded spaces is altering the way that subprocess is interpreting the first parameter. Any suggestions on how to resolve this? python2.5.2/cygwin/winxp
If you have spaces in the path, the easiest way I've found to get them interpreted properly is this. subprocess.call('""' + path + '""') I don't know why exactly it needs double double quotes, but that is what works.
Call a parent class's method from child class in Python?
When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this (super). In Perl, I might do this: package Foo; sub frotz { return "Bamf"; } package Bar; @ISA = qw(Foo); sub frotz { my $str = SUPER::frotz(); return uc($str); } In python, it appears that I have to name the parent class explicitly from the child. In the example above, I'd have to do something like Foo::frotz(). This doesn't seem right, since this behavior makes it hard to make deep hierarchies. If children need to know what class defined an inherited method, then all sorts of information pain is created. Is this an actual limitation in python, a gap in my understanding or both?
Yes, but only with new-style classes. Use the super() function: class Foo(Bar): def baz(self, arg): return super(Foo, self).baz(arg)
What is the best way to access stored procedures in Django's ORM
I am designing a fairly complex database, and know that some of my queries will be far outside the scope of Django's ORM. Has anyone integrated SP's with Django's ORM successfully? If so, what RDBMS and how did you do it?
You have to use the connection utility in Django: from django.db import connection cursor = connection.cursor() cursor.execute("SQL STATEMENT CAN BE ANYTHING") then you can fetch the data: cursor.fetchone() or: cursor.fetchall() More info here: http://docs.djangoproject.com/en/dev/topics/db/sql/
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks).
scripting languages may be slower than C, but is this a problem? almost never. and if the performance becomes a problem, you start to translate only the critical parts. twitter/ruby is a good example; ruby is slow. some of the language features (that make ruby nice in the first place) just prevent different kinds of optimization (there is a great article by the jruby guy about this ... was it ola bini? can't remember). still, twitter is powered by ruby, because ruby is fast enough. not long ago, "the blogs" reported twitter migrating to scala for performance reasons ... the truth was, only the messaging queue (and other parts of the backend) moved to scala. yahoo runs on a mixture of languages; php for the frontend, other, faster languages are used where performance is critical. so, why is performance not that important? there are several reasons: database bottleneck: not the scripting is slow, the database is clientside bottleneck: rendering in the browser takes longer than the request. optimize the server side, and nobody will notice horizontal scaling: often it's cheaper to add another server and thus triple the requests/sec than to optimize the app developer time and maintenance are the most expensive parts of your project. you'll get more cheap python devs that maintain your app than web-enabled c-coders in less time no compiling, short dev cycles another pro-scripting point: many of the scripting languages support inlining or inclusion of fast (C) code: python, inline c php: extensions in c server-side javascript via rhino: direct access to java/jvm (a good example for this is orf.at, one of the biggest websites in austria, powered by helma - serverside jvm-interpreted javascript!) i think, especially in web developement the pros of high-level scripting far outweight the cons.
How to hash a large object (dataset) in Python?
I would like to calculate a hash of a Python class containing a dataset for Machine Learning. The hash is meant to be used for caching, so I was thinking of md5 or sha1. The problem is that most of the data is stored in NumPy arrays; these do not provide a __hash__() member. Currently I do a pickle.dumps() for each member and calculate a hash based on these strings. However, I found the following links indicating that the same object could lead to different serialization strings: Hash of None varies per machine Pickle.dumps not suitable for hashing What would be the best method to calculate a hash for a Python class containing Numpy arrays?
Thanks to John Montgomery I think I have found a solution, and I think it has less overhead than converting every number in possibly huge arrays to strings: I can create a byte-view of the arrays and use these to update the hash. And somehow this seems to give the same digest as directly updating using the array: >>> import hashlib >>> import numpy >>> a = numpy.random.rand(10, 100) >>> b = a.view(numpy.uint8) >>> print a.dtype, b.dtype # a and b have a different data type float64 uint8 >>> hashlib.sha1(a).hexdigest() # byte view sha1 '794de7b1316b38d989a9040e6e26b9256ca3b5eb' >>> hashlib.sha1(b).hexdigest() # array sha1 '794de7b1316b38d989a9040e6e26b9256ca3b5eb'
Django: Redirect to previous page after login
I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work. EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks! EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this: <a href='/login/?next={{ request.path }}'>Login</a> Now I wrote a custom login view that looks somewhat like this: def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) And the important line in login.html: <form method="post" action="./?next={{ redirect_to }}"> So yeah thats pretty much it, hope that makes it clear.
You do not need to make an extra view for this, the functionality is already built in. First each page with a login link needs to know the current path, and the easiest way is to add the request context preprosessor to settings.py (the 4 first are default), then the request object will be available in each request: settings.py: TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request", ) Then add in the template you want the Login link: base.html: <a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">Login</a> This will add a GET argument to the login page that points back to the current page. The login template can then be as simple as this: registration/login.html: {% block content %} <form method="post" action=""> {{form.as_p}} <input type="submit" value="Login"> </form> {% endblock %}
Python equivalent of Perl's while (<>) {...}?
I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use while (<>) { do stuff; } This is handy because it doesn't care where the input comes from (a file or stdin). In Python I use this if len(sys.argv) == 2: # there's a command line argument sys.stdin = file(sys.argv[1]) for line in sys.stdin.readlines(): do stuff which doesn't seem very elegant. Is there a Python idiom that easily handles file/stdin input?
The fileinput module in the standard library is just what you want: import fileinput for line in fileinput.input(): ...
How to output list of floats to a binary file in Python
I have a list of floating-point values in Python: floats = [3.14, 2.7, 0.0, -1.0, 1.1] I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best. Since there are 5 values, I just want a 20-byte file as output.
Alex is absolutely right, it's more efficient to do it this way: from array import array output_file = open('file', 'wb') float_array = array('d', [3.14, 2.7, 0.0, -1.0, 1.1]) float_array.tofile(output_file) output_file.close() And then read the array like that: input_file = open('file', 'r') float_array = array('d') float_array.fromstring(input_file.read()) array.array objects also have a .fromfile method which can be used for reading the file, if you know the count of items in advance (e.g. from the file size, or some other mechanism)
Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it
I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application" - My question is how would i go about designing a program (using c#) that can be extended using Python interactively(for this to be possible, i would imagine that i would need to create some sort of a "shell" or "interactive" mode for the .net program) ? Are there any pointers on how to design .NET programs that have an interactive shell. I would then like to use python script in the shell to "extend" or interact with the program. EDIT: This question partly stems from the demo give by Miguel de Icaza during PDC 2008 where he showed the interactive csharp command prompt, C# 4.0 i think also has this "compiler as a service" feature. I looked at that and thought how cool would it be to design a windows or web program in .NET that had a interactive shell.. and a scripting language like python could be used to extend the features provided by the program. Also, i started thinking about this kind of functionality after reading one of Steve Yegge's essays where he talks about systems that live forever.
This sounds like a great use of IronPython. It's fairly easy to set up a simple scripting host from C# to allow calls into IronPython scripts, as well as allowing IronPython to call into your C# code. There are samples and examples on the CodePlex site that show how to do this very thing. Another good site for examples and samples is ironpython.info And here is a page dedicated to an example answering your very question, albeit in a generic DLR-centric way -- this would allow you to host IronPython, IronRuby, or whatever DLR languages you want to support. I've used these examples in the past to create an IronPython environment inside a private installation of ScrewTurn Wiki - it allowed me to create very expressive Wiki templates and proved to be very useful in general.
Django Manager Chaining
I was wondering if it was possible (and, if so, how) to chain together multiple managers to produce a query set that is affected by both of the individual managers. I'll explain the specific example that I'm working on: I have multiple abstract model classes that I use to provide small, specific functionality to other models. Two of these models are a DeleteMixin and a GlobalMixin. The DeleteMixin is defined as such: class DeleteMixin(models.Model): deleted = models.BooleanField(default=False) objects = DeleteManager() class Meta: abstract = True def delete(self): self.deleted = True self.save() Basically it provides a pseudo-delete (the deleted flag) instead of actually deleting the object. The GlobalMixin is defined as such: class GlobalMixin(models.Model): is_global = models.BooleanField(default=True) objects = GlobalManager() class Meta: abstract = True It allows any object to be defined as either a global object or a private object (such as a public/private blog post). Both of these have their own managers that affect the queryset that is returned. My DeleteManager filters the queryset to only return results that have the deleted flag set to False, while the GlobalManager filters the queryset to only return results that are marked as global. Here is the declaration for both: class DeleteManager(models.Manager): def get_query_set(self): return super(DeleteManager, self).get_query_set().filter(deleted=False) class GlobalManager(models.Manager): def globals(self): return self.get_query_set().filter(is_global=1) The desired functionality would be to have a model extend both of these abstract models and grant the ability to only return the results that are both non-deleted and global. I ran a test case on a model with 4 instances: one was global and non-deleted, one was global and deleted, one was non-global and non-deleted, and one was non-global and deleted. If I try to get result sets as such: SomeModel.objects.all(), I get instance 1 and 3 (the two non-deleted ones - great!). If I try SomeModel.objects.globals(), I get an error that DeleteManager doesn't have a globals (this is assuming my model declaration is as such: SomeModel(DeleteMixin, GlobalMixin). If I reverse the order, I don't get the error, but it doesn't filter out the deleted ones). If I change GlobalMixin to attach GlobalManager to globals instead of objects (so the new command would be SomeModel.globals.globals()), I get instances 1 and 2 (the two globals), while my intended result would be to only get instance 1 (the global, non-deleted one). I wasn't sure if anyone had run into any situation similar to this and had come to a result. Either a way to make it work in my current thinking or a re-work that provides the functionality I'm after would be very much appreciated. I know this post has been a little long-winded. If any more explanation is needed, I would be glad to provide it. Edit: I have posted the eventual solution I used to this specific problem below. It is based on the link to Simon's custom QuerySetManager.
See this snippet on Djangosnippets: http://djangosnippets.org/snippets/734/ Instead of putting your custom methods in a manager, you subclass the queryset itself. It's very easy and works perfectly. The only issue I've had is with model inheritance, you always have to define the manager in model subclasses (just: "objects = QuerySetManager()" in the subclass), even though they will inherit the queryset. This will make more sense once you are using QuerySetManager.
How to calculate cumulative normal distribution in Python
I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.
Here's an example: >>> from scipy.stats import norm >>> norm.cdf(1.96) array(0.97500210485177952) If you need the inverse CDF: >>> norm.ppf(norm.cdf(1.96)) array(1.9599999999999991)
Any gotchas using unicode_literals in Python 2.6?
We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding: from __future__ import unicode_literals into our .py files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spending a lot of time debugging).
The main source of problems I've had working with unicode strings is when you mix utf-8 encoded strings with unicode ones. For example, consider the following scripts. two.py # encoding: utf-8 name = 'helló wörld from two' one.py # encoding: utf-8 from __future__ import unicode_literals import two name = 'helló wörld from one' print name + two.name The output of running python one.py is: Traceback (most recent call last): File "one.py", line 5, in <module> print name + two.name UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128) In this example, two.name is an utf-8 encoded string (not unicode) since it did not import unicode_literals, and one.name is an unicode string. When you mix both, python tries to decode the encoded string (assuming it's ascii) and convert it to unicode and fails. It would work if you did print name + two.name.decode('utf-8'). The same thing can happen if you encode a string and try to mix them later. For example, this works: # encoding: utf-8 html = '<html><body>helló wörld</body></html>' if isinstance(html, unicode): html = html.encode('utf-8') print 'DEBUG: %s' % html Output: DEBUG: <html><body>helló wörld</body></html> But after adding the import unicode_literals it does NOT: # encoding: utf-8 from __future__ import unicode_literals html = '<html><body>helló wörld</body></html>' if isinstance(html, unicode): html = html.encode('utf-8') print 'DEBUG: %s' % html Output: Traceback (most recent call last): File "test.py", line 6, in <module> print 'DEBUG: %s' % html UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128) It fails because 'DEBUG: %s' is an unicode string and therefore python tries to decode html. A couple of ways to fix the print are either doing print str('DEBUG: %s') % html or print 'DEBUG: %s' % html.decode('utf-8'). I hope this helps you understand the potential gotchas when using unicode strings.
Biggest python projects
What is the biggest software development team that uses Python? I am wondering how well the dynamic type system scales to large development teams. It's pretty clear that at Google they have C++ and Java codebases with thousands of developers; their use of Python is much smaller. Are there some huge companies that develop primarily in Python?
Youtube is probably the biggest user after Google (and subsequently bought by them). Reddit, a digg-like website, is written in Python. Eve, an MMO with a good chunk written in Python is pretty impressive as well. http://en.wikipedia.org/wiki/Python_(programming_language)#Usage http://en.wikipedia.org/wiki/List_of_applications_written_in_Python
how to manually assign imagefield in Django
I have a model that has an ImageField. How can I manually assign an imagefile to it? I want it to treat it like any other uploaded file...
See the django docs for django.core.files.File Where fd is an open file object: model_instance.image_field.save('filename.jpeg', fd.read(), True)
Sqlite and Python -- return a dictionary using fetchone()?
I'm using sqlite3 in python 2.5. I've created a table that looks like this: create table votes ( bill text, senator_id text, vote text) I'm accessing it with something like this: v_cur.execute("select * from votes") row = v_cur.fetchone() bill = row[0] senator_id = row[1] vote = row[2] What I'd like to be able to do is have fetchone (or some other method) return a dictionary, rather than a list, so that I can refer to the field by name rather than position. For example: bill = row['bill'] senator_id = row['senator_id'] vote = row['vote'] I know you can do this with MySQL, but does anyone know how to do it with SQLite? Thanks!!!
There is actually an option for this in sqlite3. Change the row_factory member of the connection object to sqlite3.Row: conn = sqlite3.connect('db', row_factory=sqlite3.Row) or conn.row_factory = sqlite3.Row This will allow you to access row elements by name--dictionary-style--or by index. This is much more efficient than creating your own work-around.
Python's bz2 module not compiled by default
It seems that Python 2.6.1 doesn't compile bz2 library by default from source. I don't have lib-dynload/bz2.so What's the quickest way to add it (without installing Python from scratch)? OS is Linux 2.4.32-grsec+f6b+gr217+nfs+a32+fuse23+tg+++opt+c8+gr2b-v6.194 #1 SMP Tue Jun 6 15:52:09 PDT 2006 i686 GNU/Linux IIRC I used only --prefix flag.
You need libbz2.so (the general purpose libbz2 library) properly installed first, for Python to be able to build its own interface to it. That would typically be from a package in your Linux distro likely to have "libbz2" and "dev" in the package name.
How to debug wxpython applications?
I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info. Is there any log that I can check for the error message? (I'm running Mac OS X) or any other way? Thanks in advance for any help. Update: Here's the code that's giving me the problem... #!/usr/bin/python import wx class MyApp (wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(390, 350)) menubar = wx.MenuBar() help = wx.Menu() help.Append(ID_ABOUT, '&About') self.Bind(wx.EVT_MENU, self.OnAboutBox, id=wx.ID_ABOUT) menubar.Append(help, '&Help') self.SetMenuBar(menubar) self.Centre() self.Show(True) panel = wx.Panel(self, -1) font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(9) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) st1 = wx.StaticText(panel, -1, 'Class Name') st1.SetFont(font) hbox1.Add(st1, 0, wx.RIGHT, 8) tc = wx.TextCtrl(panel, -1) hbox1.Add(tc, 1) vbox.Add(hbox1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10) vbox.Add((-1, 10)) hbox2 = wx.BoxSizer(wx.HORIZONTAL) st2 = wx.StaticText(panel, -1, 'Matching Classes') st2.SetFont(font) hbox2.Add(st2, 0) vbox.Add(hbox2, 0, wx.LEFT | wx.TOP, 10) vbox.Add((-1, 10)) hbox3 = wx.BoxSizer(wx.HORIZONTAL) tc2 = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE) hbox3.Add(tc2, 1, wx.EXPAND) vbox.Add(hbox3, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 10) vbox.Add((-1, 25)) hbox4 = wx.BoxSizer(wx.HORIZONTAL) cb1 = wx.CheckBox(panel, -1, 'Case Sensitive') cb1.SetFont(font) hbox4.Add(cb1) cb2 = wx.CheckBox(panel, -1, 'Nested Classes') cb2.SetFont(font) hbox4.Add(cb2, 0, wx.LEFT, 10) cb3 = wx.CheckBox(panel, -1, 'Non-Project classes') cb3.SetFont(font) hbox4.Add(cb3, 0, wx.LEFT, 10) vbox.Add(hbox4, 0, wx.LEFT, 10) vbox.Add((-1, 25)) hbox5 = wx.BoxSizer(wx.HORIZONTAL) btn1 = wx.Button(panel, -1, 'Ok', size=(70, 30)) hbox5.Add(btn1, 0) btn2 = wx.Button(panel, -1, 'Close', size=(70, 30)) hbox5.Add(btn2, 0, wx.LEFT | wx.BOTTOM , 5) vbox.Add(hbox5, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10) panel.SetSizer(vbox) self.Centre() self.Show(True) def OnAboutBox(self, event): description = """ describe my app here """ licence = """ blablabla """ info = wx.AboutDialogInfo() info.SetIcon(wx.Icon('icons/icon.png', wx.BITMAP_TYPE_PNG)) info.SetName('') info.SetVersion('1.0') info.SetDescription(description) info.SetCopyright('') info.SetWebSite('') info.SetLicence(licence) info.AddDeveloper('') info.AddDocWriter('') info.AddArtist('') info.AddTranslator('') wx.AboutBox(info) app = wx.App() MyApp (None, -1, 'Go To Class') app.MainLoop()
not sure about the mac version, but wxPython has a built in way to redirect errors to a window (which will unfortunately close when your application crashes, but it's useful for catching errors that silently fail) or to a log file (only updated after your application closes): app = wx.App(redirect=True) app = wx.App(redirect=True,filename="mylogfile.txt") these will work regardless of how you start your application. See here for more
Embedding a Python shell inside a Python program
I am making a sort of a science lab in Python, in which the user can create, modify and analyze all sorts of objects. I would like to put a Python shell inside the program, so the user could manipulate the objects through the shell. (Note: He could also manipulate the objects through the usual GUI.) A mockup that illustrates this: How can I make this sort of thing? I considered using eval, but I understood that eval can't handle import, for example.
You are looking for code - Interpreter base classes, particularly code.interact(). Some examples from effbot.
Easiest way to rm -rf in Python
What is the easiest way to do the equivalent of rm -rf in Python?
import shutil shutil.rmtree("dir-you-want-to-remove")
Is there a decorator to simply cache function return values?
Consider the following: @property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;) PS the real calculation doesn't depend on mutable values
Starting from Python 3.2 there is a built-in decorator: @functools.lru_cache(maxsize=100, typed=False) Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments. Example of an LRU cache for computing Fibonacci numbers: @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) >>> print([fib(n) for n in range(16)]) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] >>> print(fib.cache_info()) CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) If you are stuck with Python 2.x, here's a list of other compatible memoization libraries: functools32 | PyPI | Source code repoze.lru | PyPI | Source code pylru | PyPI | Source code backports.functools_lru_cache | PyPI | Source code
Where is Python's "best ASCII for this Unicode" database?
I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them all into "?" ?
Unidecode looks like a complete solution. It converts fancy quotes to ascii quotes, accented latin characters to unaccented and even attempts transliteration to deal with characters that don't have ASCII equivalents. That way your users don't have to see a bunch of ? when you had to pass their text through a legacy 7-bit ascii system. >>> from unidecode import unidecode >>> print unidecode(u"\u5317\u4EB0") Bei Jing http://www.tablix.org/~avian/blog/archives/2009/01/unicode%5Ftransliteration%5Fin%5Fpython/
Python: avoiding pylint warnings about too many arguments
I want to refactor a big Python function into smaller ones. For example, consider this following code snippet: x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like: def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9): x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like: def mysum(d): x1 = d['x1'] x2 = d['x2'] ... x9 = d['x9'] x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x def mybigfunction(): ... d = {} d['x1'] = x1 ... d['x9'] = x9 x = mysum(d) but this approach loos ugly to me, it requires writing a lot of code that is even redundant. Is there a better way to do it?
First, one of Perlis's epigrams: "If you have a procedure with 10 parameters, you probably missed some." Some of the 10 arguments are presumably related. Group them into an object, and pass that instead. Making an example up, because there's not enough information in the question to answer directly: class PersonInfo(object): def __init__(self, name, age, iq): self.name = name self.age = age self.iq = iq Then your 10 argument function: def f(x1, x2, name, x3, iq, x4, age, x5, x6, x7): ... becomes: def f(personinfo, x1, x2, x3, x4, x5, x6, x7): ... and the caller changes to: personinfo = PersonInfo(name, age, iq) result = f(personinfo, x1, x2, x3, x4, x5, x6, x7)
Call a function with argument list in python
I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this: def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) In this case first call will work, and second won't. What I want to modify is the wrapper function and not the called functions.
To expand a little on the other answers: In the line: def wrapper(func, *args): The * next to args means "take the rest of the parameters given and put them in a list called args". In the line: func(*args) The * next to args here means "take this list called args and 'unwrap' it into the rest of the parameters. So you can do the following: def wrapper1(func, *args): # with star func(*args) def wrapper2(func, args): # without star func(*args) def func2(x, y, z): print x+y+z wrapper1(func2, 1, 2, 3) wrapper2(func2, [1, 2, 3]) In wrapper2, the list is passed explicitly, but in both wrappers args contains the list [1,2,3].
Overriding the save method in Django ModelForm
I'm having trouble overriding a ModelForm save method. This is the error I'm receiving: Exception Type: TypeError Exception Value: save() got an unexpected keyword argument 'commit' My intentions are to have a form submit many values for 3 fields, to then create an object for each combination of those fields, and to save each of those objects. Helpful nudge in the right direction would be ace. File models.py class CallResultType(models.Model): id = models.AutoField(db_column='icontact_result_code_type_id', primary_key=True) callResult = models.ForeignKey('CallResult', db_column='icontact_result_code_id') campaign = models.ForeignKey('Campaign', db_column='icampaign_id') callType = models.ForeignKey('CallType', db_column='icall_type_id') agent = models.BooleanField(db_column='bagent', default=True) teamLeader = models.BooleanField(db_column='bTeamLeader', default=True) active = models.BooleanField(db_column='bactive', default=True) File forms.py from django.forms import ModelForm, ModelMultipleChoiceField from callresults.models import * class CallResultTypeForm(ModelForm): callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all()) campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all()) callType = ModelMultipleChoiceField(queryset=CallType.objects.all()) def save(self, force_insert=False, force_update=False): for cr in self.callResult: for c in self.campain: for ct in self.callType: m = CallResultType(self) # this line is probably wrong m.callResult = cr m.campaign = c m.calltype = ct m.save() class Meta: model = CallResultType File admin.py class CallResultTypeAdmin(admin.ModelAdmin): form = CallResultTypeForm
In your save you have to have the argument commit. If anything overrides your form, or wants to modify what it's saving, it will do save(commit=False), modify the output, and then save it itself. Also, your ModelForm should return the model it's saving. Usually a ModelForm's save will look something like: def save(self, commit=True): m = super(CallResultTypeForm, self).save(commit=False) # do custom stuff if commit: m.save() return m Read up on the save method. Finally, a lot of this ModelForm won't work just because of the way you are accessing things. Instead of self.callResult, you need to use self.fields['callResult']. UPDATE: In response to your answer: Aside: Why not just use ManyToManyFields in the Model so you don't have to do this? Seems like you're storing redundant data and making more work for yourself (and me :P). from django.db.models import AutoField def copy_model_instance(obj): """ Create a copy of a model instance. M2M relationships are currently not handled, i.e. they are not copied. (Fortunately, you don't have any in this case) See also Django #4027. From http://blog.elsdoerfer.name/2008/09/09/making-a-copy-of-a-model-instance/ """ initial = dict([(f.name, getattr(obj, f.name)) for f in obj._meta.fields if not isinstance(f, AutoField) and not f in obj._meta.parents.values()]) return obj.__class__(**initial) class CallResultTypeForm(ModelForm): callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all()) campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all()) callType = ModelMultipleChoiceField(queryset=CallType.objects.all()) def save(self, commit=True, *args, **kwargs): m = super(CallResultTypeForm, self).save(commit=False, *args, **kwargs) results = [] for cr in self.callResult: for c in self.campain: for ct in self.callType: m_new = copy_model_instance(m) m_new.callResult = cr m_new.campaign = c m_new.calltype = ct if commit: m_new.save() results.append(m_new) return results This allows for inheritance of CallResultTypeForm, just in case that's ever necessary.
Python's random: What happens if I don't use seed(someValue)?
a)In this case does the random number generator uses the system's clock (making the seed change) on each run? b)Is the seed used to generate the pseudo-random values of expovariate(lambda)?
"Use the Source, Luke!"...;-). Studying http://svn.python.org/view/python/trunk/Lib/random.py?revision=68378&view=markup will rapidly reassure you;-). What happens when seed isn't set (that's the "i is None" case): if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) # use fractional seconds and the expovariate: random = self.random u = random() while u <= 1e-7: u = random() return -_log(u)/lambd obviously uses the same underlying random generator as every other method, and so is identically affected by the seeding or lack thereof (really, how else would it have been done?-)
Unique session id in python
How do I generate a unique session id in Python?
I hate to say this, but none of the other solutions posted here are correct with regards to being a "secure session ID." # pip install M2Crypto import base64, M2Crypto def generate_session_id(num_bytes = 16): return base64.b64encode(M2Crypto.m2.rand_bytes(num_bytes)) Neither uuid() or os.urandom() are good choices for generating session IDs. Both may generate random results, but random does not mean it is secure due to poor entropy. See "How to Crack a Linear Congruential Generator" by Haldir or NIST's resources on Random Number Generation. If you still want to use a UUID, then use a UUID that was generated with a good initial random number: import uuid, M2Crypto uuid.UUID(bytes = M2Crypto.m2.rand_bytes(num_bytes))) # UUID('5e85edc4-7078-d214-e773-f8caae16fe6c') or: # pip install pyOpenSSL import uuid, OpenSSL uuid.UUID(bytes = OpenSSL.rand.bytes(16)) # UUID('c9bf635f-b0cc-d278-a2c5-01eaae654461') M2Crypto is best OpenSSL API in Python atm as pyOpenSSL appears to be maintained only to support legacy applications.
Letting users upload Python scripts for execution
I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I either need a solution to ensure a user couldn't compromise any other files or inject malicious code via their uploaded script or a solution for client-side execution of the game. Any suggestions? (I'm looking for a solution that will work with my Python scripts)
I am in no way associated with this site and I'm only linking it because it tries to achieve what you are getting after: jailing of python. The site is code pad. According to the about page it is ran under geordi and traps all sys calls with ptrace. In addition to be chroot'ed they are on a virtual machine with firewalls in place to disallow outbound connections. Consider it a starting point but I do have to chime in on the whole danger thing. Gotta CYA myself. :)
Is it possible to implement a Python for range loop without an iterator variable?
Is is possible to do this; for i in range(some_number): #do something without the i? If you just want to do something x amount of times and don't need the iterator.
Off the top of my head, no. I think the best you could do is something like this: def loop(f,n): for i in xrange(n): f() loop(lambda: <insert expression here>, 5) But I think you can just live with the extra i variable. Here is the option to use the _ variable, which in reality, is just another variable. for _ in range(n): do_something() Note that _ is assigned the last result that returned in an interactive python session: >>> 1+2 3 >>> _ 3 For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter. >>> for _ in xrange(10): pass ... >>> _ 9 >>> 1+2 3 >>> _ 9 And according to python grammar, it is an acceptable variable name: identifier ::= (letter|"_") (letter | digit | "_")*
How can I check if an ip is in a network in python
Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python? Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.
I like to use netaddr for that: from netaddr import CIDR, IP if IP("192.168.0.1") in CIDR("192.168.0.0/24"): print "Yay!" As arno_v pointed out in the comments, new version of netaddr does it like this: from netaddr import IPNetwork, IPAddress if IPAddress("192.168.0.1") in IPNetwork("192.168.0.0/24"): print "Yay!"
python, __slots__, and "attribute is read-only"
I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows: class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # create one a.m = "?" # here is a PROBLEM But after running this simple code, I get a very strange error: Traceback (most recent call last): File "test.py", line 8, in <module> a.m = "?" AttributeError: 'test' object attribute 'm' is read-only Is there any wise programmer who can spare a bit of their time and enlighten me about "read-only" errors?
When you declare instance variables using __slots__, Python creates a descriptor object as a class variable with the same name. In your case, this descriptor is overwritten by the class variable m that you are defining at the following line: m = None # my attribute Here is what you need to do: Do not define a class variable called m, and initialize the instance variable m in the __init__ method. class MyClass(object): __slots__ = ("m",) def __init__(self): self.m = None a = MyClass() a.m = "?" As a side note, tuples with single elements need a comma after the element. Both work in your code because __slots__ accepts a single string or an iterable/sequence of strings. In general, to define a tuple containing the element 1, use (1,) or 1, and not (1).
Python sockets buffering
Let's say I want to read a line from a socket, using the standard socket module: def read_line(s): ret = '' while True: c = s.recv(1) if c == '\n' or c == '': break else: ret += c return ret What exactly happens in s.recv(1)? Will it issue a system call each time? I guess I should add some buffering, anyway: For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096. http://docs.python.org/library/socket.html#socket.socket.recv But it doesn't seem easy to write efficient and thread-safe buffering. What if I use file.readline()? # does this work well, is it efficiently buffered? s.makefile().readline()
If you are concerned with performance and control the socket completely (you are not passing it into a library for example) then try implementing your own buffering in Python -- Python string.find and string.split and such can be amazingly fast. def linesplit(socket): buffer = socket.recv(4096) buffering = True while buffering: if "\n" in buffer: (line, buffer) = buffer.split("\n", 1) yield line + "\n" else: more = socket.recv(4096) if not more: buffering = False else: buffer += more if buffer: yield buffer If you expect the payload to consist of lines that are not too huge, that should run pretty fast, and avoid jumping through too many layers of function calls unnecessarily. I'd be interesting in knowing how this compares to file.readline() or using socket.recv(1).
How do I iterate over the HTML attributes of a Beautiful Soup element?
How do I iterate over the HTML attributes of a Beautiful Soup element? Like, given: <foo bar="asdf" blah="123">xyz</foo> I want "bar" and "blah".
from BeautifulSoup import BeautifulSoup page = BeautifulSoup('<foo bar="asdf" blah="123">xyz</foo>') for attr, value in page.find('foo').attrs: print attr, "=", value # Prints: # bar = asdf # blah = 123
Yaml merge in Python
So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file. So I was thinking it would be useful if the library provided a default yaml tree and merged it with a user supplied one. For usability sake I wonder if possible there are any out there who can divine a routine where: In any case in the tree where the user supplied yaml overlaps the default, the user supplied branches replace the library supplied ones. In any case where the user supplied yaml does not overlap the default tree, the default tree persists. Any superflous branches in the tree provided by the user supplied yaml are appended. I know this explanation was verbose as it is probably clear what I'm asking for. I wonder if it is a bit much to get for free.
You could use PyYAML for parsing the files, and then the following function to merge two trees: def merge(user, default): if isinstance(user,dict) and isinstance(default,dict): for k,v in default.iteritems(): if k not in user: user[k] = v else: user[k] = merge(user[k],v) return user Optionally, you could do a deep-copy of the user-tree before calling this function.
Extract domain name from a host name
Is there a programatic way to find the domain name from a given hostname? given -> www.yahoo.co.jp return -> yahoo.co.jp The approach that works but is very slow is: split on "." and remove 1 group from the left, join and query an SOA record using dnspython when a valid SOA record is returned, consider that a domain Is there a cleaner/faster way to do this without using regexps?
There's no trivial definition of which "domain name" is the parent of any particular "host name". Your current method of traversing up the tree until you see an SOA record is actually the most correct. Technically, what you're doing there is finding a "zone cut", and in the vast majority of cases that will correspond to the point at which the domain was delegated from its TLD. Any method that relies on mere text parsing of the host name without reference to the DNS is doomed to failure. Alternatively, make use of the centrally maintained lists of delegation-centric domains from http://publicsuffix.org/, but beware that these lists can be incomplete and/or out of date. See also this question where all of this has been gone over before...
Abstract class + mixin + multiple inheritance in python
So, I think the code probably explains what I'm trying to do better than I can in words, so here goes: import abc class foo(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def bar(self): pass class bar_for_foo_mixin(object): def bar(self): print "This should satisfy the abstract method requirement" class myfoo(foo, bar_for_foo_mixin): def __init__(self): print "myfoo __init__ called" self.bar() obj = myfoo() The result: TypeError: Can't instantiate abstract class myfoo with abstract methods bar I'm trying to get the mixin class to satisfy the requirements of the abstract/interface class. What am I missing?
Shouldn't the inheritance be the other way round? In the MRO foo currently comes before bar_for_foo_mixin, and then rightfully complains. With class myfoo(bar_for_foo_mixin, foo) it should work. And I am not sure if your class design is the right way to do it. Since you use a mixin for implementing bar it might be better not to derive from foo and just register it with the 'foo' class (i.e. foo.register(myfoo)). But this is just my gut feeling. For completeness, here is the documentation for ABCs.
Python: finding uid/gid for a given username/groupname (for os.chown)
What's a good way to find the uid/gid for a given username or groupname using Python? I need to set file ownership with os.chown and need the integer ids instead of the alphabetic. [Quick note]: getpwnam works great but is not available on windows, so here's some code that creates stubs to allow you to run the same code on windows and unix. try: from pwd import getpwnam except: getpwnam = lambda x: (0,0,0) os.chown = lambda x, y, z: True os.chmod = lambda x, y: True os.fchown = os.chown os.fchmod = os.chmod
Use the pwd and grp modules: from pwd import getpwnam print getpwnam('someuser')[2] # or print getpwnam('someuser').pw_uid
Python: Mixing files and loops
I'm writing a script that logs errors from another program and restarts the program where it left off when it encounters an error. For whatever reasons, the developers of this program didn't feel it necessary to put this functionality into their program by default. Anyways, the program takes an input file, parses it, and creates an output file. The input file is in a specific format: UI - 26474845 TI - the title (can be any number of lines) AB - the abstract (can also be any number of lines) When the program throws an error, it gives you the reference information you need to track the error - namely, the UI, which section (title or abstract), and the line number relative to the beginning of the title or abstract. I want to log the offending sentences from the input file with a function that takes the reference number and the file, finds the sentence, and logs it. The best way I could think of doing it involves moving forward through the file a specific number of times (namely, n times, where n is the line number relative to the beginning of the seciton). The way that seemed to make sense to do this is: i = 1 while i <= lineNumber: print original.readline() i += 1 I don't see how this would make me lose data, but Python thinks it would, and says ValueError: Mixing iteration and read methods would lose data. Does anyone know how to do this properly?
You get the ValueError because your code probably has for line in original: in addition to original.readline(). An easy solution which fixes the problem without making your program slower or consume more memory is changing for line in original: ... to while True: line = original.readline() if not line: break ...
Is there a way to list all the available drive letters in python?
More or less what it says on the tin: is there an (easy) way in Python to list all the currently in-use drive letters in a windows system? (My google-fu seems to have let me down on this one.) Related: Enumerating all available drive letters in Windows (C++ / Win32)
Without using any external libraries, if that matters to you: import string from ctypes import windll def get_drives(): drives = [] bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if bitmask & 1: drives.append(letter) bitmask >>= 1 return drives if __name__ == '__main__': print get_drives() # On my PC, this prints ['A', 'C', 'D', 'F', 'H']
How do you validate a URL with a regular expression in Python?
I'm building an app on Google App Engine. I'm incredibly new to Python and have been beating my head against the following problem for the past 3 days. I have a class to represent an RSS Feed and in this class I have a method called setUrl. Input to this method is a URL. I'm trying to use the re python module to validate off of the RFC 3986 Reg-ex (http://www.ietf.org/rfc/rfc3986.txt) Below is a snipped which should work? p = re.compile('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?') m = p.match(url) if m: self.url = url return url
Here's the complete regexp to parse a URL. (?:http://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\. )*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+) ){3}))(?::(?:\d+))?)(?:/(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F \d]{2}))|[;:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{ 2}))|[;:@&=])*))*)(?:\?(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{ 2}))|[;:@&=])*))?)?)|(?:ftp://(?:(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(? :%[a-fA-F\d]{2}))|[;?&=])*)(?::(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a- fA-F\d]{2}))|[;?&=])*))?@)?(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|- )*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(? :\d+)(?:\.(?:\d+)){3}))(?::(?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:(?:/(?:(?:(?:(?:(?:[a-zA-Z\d\$\-_.!~*' (),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(), ])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))?)|(?:/(?:(?:(?:(?:(?:[a-zA-Z\d \$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\ -_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?))|(?:(?:(?:(?:(?:[a-zA- Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d \$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?))) Given its complexibility, I think you should go the urlparse way. For completeness, here's the pseudo-BNF of the above regex (as a documentation): ; The generic form of a URL is: genericurl = scheme ":" schemepart ; Specific predefined schemes are defined here; new schemes ; may be registered with IANA url = httpurl | ftpurl | newsurl | nntpurl | telneturl | gopherurl | waisurl | mailtourl | fileurl | prosperourl | otherurl ; new schemes follow the general syntax otherurl = genericurl ; the scheme is in lower case; interpreters should use case-ignore scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] schemepart = *xchar | ip-schemepart ; URL schemeparts for ip based protocols: ip-schemepart = "//" login [ "/" urlpath ] login = [ user [ ":" password ] "@" ] hostport hostport = host [ ":" port ] host = hostname | hostnumber hostname = *[ domainlabel "." ] toplabel domainlabel = alphadigit | alphadigit *[ alphadigit | "-" ] alphadigit toplabel = alpha | alpha *[ alphadigit | "-" ] alphadigit alphadigit = alpha | digit hostnumber = digits "." digits "." digits "." digits port = digits user = *[ uchar | ";" | "?" | "&" | "=" ] password = *[ uchar | ";" | "?" | "&" | "=" ] urlpath = *xchar ; depends on protocol see section 3.1 ; The predefined schemes: ; FTP (see also RFC959) ftpurl = "ftp://" login [ "/" fpath [ ";type=" ftptype ]] fpath = fsegment *[ "/" fsegment ] fsegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ] ftptype = "A" | "I" | "D" | "a" | "i" | "d" ; FILE fileurl = "file://" [ host | "localhost" ] "/" fpath ; HTTP httpurl = "http://" hostport [ "/" hpath [ "?" search ]] hpath = hsegment *[ "/" hsegment ] hsegment = *[ uchar | ";" | ":" | "@" | "&" | "=" ] search = *[ uchar | ";" | ":" | "@" | "&" | "=" ] ; GOPHER (see also RFC1436) gopherurl = "gopher://" hostport [ / [ gtype [ selector [ "%09" search [ "%09" gopher+_string ] ] ] ] ] gtype = xchar selector = *xchar gopher+_string = *xchar ; MAILTO (see also RFC822) mailtourl = "mailto:" encoded822addr encoded822addr = 1*xchar ; further defined in RFC822 ; NEWS (see also RFC1036) newsurl = "news:" grouppart grouppart = "*" | group | article group = alpha *[ alpha | digit | "-" | "." | "+" | "_" ] article = 1*[ uchar | ";" | "/" | "?" | ":" | "&" | "=" ] "@" host ; NNTP (see also RFC977) nntpurl = "nntp://" hostport "/" group [ "/" digits ] ; TELNET telneturl = "telnet://" login [ "/" ] ; WAIS (see also RFC1625) waisurl = waisdatabase | waisindex | waisdoc waisdatabase = "wais://" hostport "/" database waisindex = "wais://" hostport "/" database "?" search waisdoc = "wais://" hostport "/" database "/" wtype "/" wpath database = *uchar wtype = *uchar wpath = *uchar ; PROSPERO prosperourl = "prospero://" hostport "/" ppath *[ fieldspec ] ppath = psegment *[ "/" psegment ] psegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ] fieldspec = ";" fieldname "=" fieldvalue fieldname = *[ uchar | "?" | ":" | "@" | "&" ] fieldvalue = *[ uchar | "?" | ":" | "@" | "&" ] ; Miscellaneous definitions lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" hialpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" alpha = lowalpha | hialpha digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" safe = "$" | "-" | "_" | "." | "+" extra = "!" | "*" | "'" | "(" | ")" | "," national = "{" | "}" | "|" | "\" | "^" | "~" | "[" | "]" | "`" punctuation = "" | "#" | "%" | reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f" escape = "%" hex hex unreserved = alpha | digit | safe | extra uchar = unreserved | escape xchar = unreserved | reserved | escape digits = 1*digit
Launch a webpage on a Firefox (win) tab using Python
I'm trying to launch a website url in a new tab using python in that way, but it didn't worked in these both ways: Method 1: os.system('C:\Program Files\Mozilla Firefox\Firefox.exe -new-tab http://www.google.com/'); and Method 2: os.startfile('C:\Program Files\Mozilla Firefox\Firefox.exe -new-tab http://www.google.com/'); If I don't add the parameters (-new-tab http://www.google.com/) it works, opening the default page.
You need to use the webbrowser module import webbrowser webbrowser.open('http://www.google.com') [edit] If you want to open a url in a non-default browser try: webbrowser.get('firefox').open_new_tab('http://www.google.com')
I need a sample of python unit testing sqlalchemy model with nose
Can someone show me how to write unit tests for sqlalchemy model I created using nose. I just need one simple example. Thanks.
You can simply create an in-memory SQLite database and bind your session to that. Example: from db import session # probably a contextbound sessionmaker from db import model from sqlalchemy import create_engine def setup(): engine = create_engine('sqlite:///:memory:') session.configure(bind=engine) # You probably need to create some tables and # load some test data, do so here. # To create tables, you typically do: model.metadata.create_all(engine) def teardown(): session.remove() def test_something(): instances = session.query(model.SomeObj).all() eq_(0, len(instances)) session.add(model.SomeObj()) session.flush() # ...
Returning http status codes in Python CGI
Is it possible to send a status code other than 200 via a python cgi script (such as 301 redirect)
via cgi script? print "Status:301\nLocation: http://www.google.com"
Python dictionary: are keys() and values() always the same order?
It looks like the lists returned by keys() and values() methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods). For example: >>> d = {'one':1, 'two': 2, 'three': 3} >>> k, v = d.keys(), d.values() >>> for i in range(len(k)): print d[k[i]] == v[i] True True True If you do not alter the dictionary between calling keys() and calling values(), is it wrong to assume the above for-loop will always print True? I could not find any documentation confirming this.
Found this: If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. On 2.x documentation and 3.x documentation.
Extending Python's builtin Str
I'm trying to subclass str, but having some difficulties due to its immutability. class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): #overridden, new functionality. Return ob of type DerivedClass. Great. caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') derived = DerivedClass('a') print derived.upper() #'A123' print type(derived.upper()) #<class '__main__.DerivedClass'> print derived.lower() #'a' print type(derived.lower()) #<type 'str'> For inherited methods that don't require any new functionality, such as derived.lower(), is there a simple, pythonic way to return an object of type DerivedClass (instead of str)? Or am I stuck manually overriding each str.method(), as I did with derived.upper()? Edit: #Any massive flaws in the following? class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') def __getattribute__(self, name): att = super(DerivedClass, self).__getattribute__(name) if not callable(att): return att def call_me_later(*args, **kwargs): result = att(*args, **kwargs) if isinstance(result, basestring): return DerivedClass(result) return result return call_me_later
Good use for a class decorator -- roughly (untested code): @do_overrides class Myst(str): def upper(self): ...&c... and def do_overrides(cls): done = set(dir(cls)) base = cls.__bases__[0] def wrap(f): def wrapper(*a, **k): r = f(*a, **k) if isinstance(r, base): r = cls(r) return r for m in dir(base): if m in done or not callable(m): continue setattr(cls, m, wrap(getattr(base, m)))
How can I tell if a python variable is a string or a list?
I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example: def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated like ['file1'] How can my function tell whether a string or a list has been passed in? I know there is a type function, but is there a "more pythonic" way?
isinstance(your_var, basestring)
How do I create a slug in Django?
I am trying to create a SlugField in Django. I created this simple model: from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() I then do this: >>> from mysite.books.models import Test >>> t=Test(q="aa a a a", s="b b b b") >>> t.s 'b b b b' >>> t.save() >>> t.s 'b b b b' >>> I was expecting b-b-b-b
You will need to use the slugify function. >>> from django.template.defaultfilters import slugify >>> slugify("b b b b") u'b-b-b-b' >>> You can call slugify automatically by overriding the save method: class test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() def save(self, *args, **kwargs): self.s = slugify(self.q) super(test, self).save(*args, **kwargs) Be aware that the above will cause your URL to change when the q field is edited, which can cause broken links. It may be preferable to generate the slug only once when you create a new object: class test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() def save(self, *args, **kwargs): if not self.id: # Newly created object, so set slug self.s = slugify(self.q) super(test, self).save(*args, **kwargs)
Working with subdomain in google app engine
How can I work with sub domain in google app engine (python). I wanna get first domain part and take some action (handler). Example:      product.example.com -> send it to products handler      user.example.com -> send it to users handler Actually, using virtual path I have this code: application = webapp.WSGIApplication( [('/', IndexHandler), ('/product/(.*)', ProductHandler), ('/user/(.*)', UserHandler) ] Did I make my self clear? (sorry poor english)
WSGIApplication isn't capable of routing based on domain. Instead, you need to create a separate application for each subdomain, like this: applications = { 'product.example.com': webapp.WSGIApplication([ ('/', IndexHandler), ('/(.*)', ProductHandler)]), 'user.example.com': webapp.WSGIApplication([ ('/', IndexHandler), ('/(.*)', UserHandler)]), } def main(): run_wsgi_app(applications[os.environ['HTTP_HOST']]) if __name__ == '__main__': main() Alternately, you could write your own WSGIApplication subclass that knows how to handle multiple hosts.
Python dictionary deepcopy
I was wondering in how does exactly deepcopy work in the following context: from copy import deepcopy def copyExample: self.myDict = {} firstPosition = "First" firstPositionContent = ["first", "primero"] secondPosition = "Second" secondPositionContent = ["second"] self.myDict[firstPosition] = firstPositionContent self.myDict[secondPosition] = secondPositionContent return deepcopy(self.myDict) def addExample(self): copy = self.copyExample() copy["Second"].add("segundo") Does it return the reference to the lists I have in the dictionary? Or does it work as I expect and copy every list in a new list with a different reference? I know what a deep copy is (so there is no need to explain the difference between deep and shallow) but I am wondering if it works as I expect it to do and therefore do not change the instance variable when I use addExample().
The documentation makes it pretty clear that you're getting new copies, not references. Deepcopy creates deep copies for built in types, with various exceptions and that you can add custom copy operations to your user-defined objects to get deep copy support for them as well. If you're not sure, well that's what unit testing is for.
cursor.rowcount always -1 in sqlite3 in python3k
I am trying to get the rowcount of a sqlite3 cursor in my Python3k program, but I am puzzled, as the rowcount is always -1, despite what Python3 docs say (actually it is contradictory, it should be None). Even after fetching all the rows, rowcount stays at -1. Is it a sqlite3 bug? I have already checked if there are rows in the table. I can get around this checking if a fetchone() returns something different than None, but I thought this issue would be nice to discuss. Thanks.
From the documentation: As required by the Python DB API Spec, the rowcount attribute “is -1 in case no executeXX() has been performed on the cursor or the rowcount of the last operation is not determinable by the interface”. This includes SELECT statements because we cannot determine the number of rows a query produced until all rows were fetched. That means all SELECT statements won't have a rowcount. The behaviour you're observing is documented. EDIT: Documentation doesn't say anywhere that rowcount will be updated after you do a fetchall() so it is just wrong to assume that.
Twisted and p2p applications
Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?
The best solution is to use the source code for BitTorrent. It was built with Twisted until they switched over to a C++ implementation called Utorrent. Last known Twisted version of BitTorrent http://download.bittorrent.com/dl/archive/BitTorrent-5.2.2.tar.gz Older versions http://download.bittorrent.com/dl/archive/ As an alternative, you also might want to take a look at Vertex. It is a p2p library built on top of Twisted and comes with goodies like bypassing firewalls. Its probably more complete than the other people's sample. Link to Vertex https://github.com/twisted/vertex
Best Practices for Python Exceptions?
What are the best practices for creating exceptions? I just saw this, and I don't know if I should be horrified, or like it. I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this? Basically from my understanding from the scripts is that this was done so all the inhouse Python libraries will have a common error message format (something that is desperately needed) so I can understand why putting the error message string is a good idea. (Almost every method throws exceptions due to the utter need for nothing invalid getting through). The code in question is the following: """ Base Exception, Error """ class Error(Exception): def __init__(self, message): self.message = message def __str__(self): return "[ERROR] %s\n" % str(self.message) def log(self): ret = "%s" % str(self.message) if(hasattr(self, "reason")): return "".join([ret, "\n==> %s" % str(self.reason)]) return ret class PCSException(Error): def __init__(self, message, reason = None): self.message = message self.reason = reason def __str__(self): ret = "[PCS_ERROR] %s\n" % str(self.message) if(self.reason != None): ret += "[REASON] %s\n" % str(self.reason) return ret This is just the tip of the iceberg, but can someone give me some insight in what makes this a terrible idea? Or if there is a much better exception coding process/style.
Robust exception handling (in Python) - a "best practices for Python exceptions" blog post I wrote a while ago. You may find it useful. Some key points from the blog: Never use exceptions for flow-control Exceptions exist for exceptional situations: events that are not a part of normal execution. Consider 'find' on a string returning -1 if the pattern isn't found, but indexing beyond the end of a string raises an exception. Not finding the string is normal execution. Handle exceptions at the level that knows how to handle them ... The best place is that piece of code that can handle the exception. For some exceptions, like programming errors (e.g. IndexError, TypeError, NameError etc.) exceptions are best left to the programmer / user, because "handling" them will just hide real bugs. Always ask "is this the right place to handle this exception?" and be careful with catching all exceptions. Document the exceptions thrown by your code ... thinking about which exceptions your code may throw will help you write better, safer and more encapsulated code
How do you alias a python class to have another name without using inheritance?
If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance? e.g. I have a class like: class MyReallyBigClassNameWhichIHateToType: def __init__(self): <blah> [...] I'm creating an interactive console session where I don't want my users' fingers to fall off while instantiating the class in the interactive sessions, so I want to alias that really long class name to something tiny like 'C'. Is there an easy way to do this without inheritance?
C = MyReallyBigClassNameWhichIHateToType
Django equivalent of COUNT with GROUP BY
I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query: SELECT player_type, COUNT(*) FROM players GROUP BY player_type; Is it possible with Django 1.1's Model Query API or should I just use plain SQL?
If you are using Django 1.1 beta (trunk): Player.objects.values('player_type').order_by().annotate(Count('player_type')) values('player_type') - for inclusion only player_type field into GROUP BY clause. order_by() - for exclusion possible default ordering that can cause not needed fields inclusion in SELECT and GROUP BY.
Is there a portable way to get the current username in Python?
Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like os.getuid: >>> os.getuid() 42 >>> os.getusername() 'slartibartfast' I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The pwd module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.
Look at getpass module import getpass getpass.getuser() 'kostya' Availability: Unix, Windows p.s. Per comment below "this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other)."
Practical GUI toolkit?
I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; FOX, wx, Tk or Qt?
I would go with Qt. It works on all the major platforms, and it's being continually improved. You can also get started really fast. There are bindings for Java, Ruby and Python. Plus it's free if you're writing open source programs.
Which is more accurate, x**.5 or math.sqrt(x)?
I recently discovered that x**.5 and math.sqrt(x) do not always produce the same result in Python: Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 >>> 8885558**.5 - math.sqrt(8885558) -4.5474735088646412e-13 Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers. So the question is, which method is more accurate?
Neither one is more accurate, they both diverge from the actual answer in equal parts: >>> (8885558**0.5)**2 8885557.9999999981 >>> sqrt(8885558)**2 8885558.0000000019 >>> 2**1023.99999999999 1.7976931348498497e+308 >>> (sqrt(2**1023.99999999999))**2 1.7976931348498495e+308 >>> ((2**1023.99999999999)**0.5)**2 1.7976931348498499e+308 >>> ((2**1023.99999999999)**0.5)**2 - 2**1023.99999999999 1.9958403095347198e+292 >>> (sqrt(2**1023.99999999999))**2 - 2**1023.99999999999 -1.9958403095347198e+292 http://mail.python.org/pipermail/python-list/2003-November/238546.html The math module wraps the platform C library math functions of the same names; math.pow() is most useful if you need (or just want) high compatibility with C extensions calling C's pow(). __builtin__.pow() is the implementation of Python's infix ** operator, and deals with complex numbers, unbounded integer powers, and modular exponentiation too (the C pow() doesn't handle any of those). ** is more complete. math.sqrt is probably just the C implementation of sqrt which is probably related to pow.
How to prevent a block of code from being interrupted by KeyboardInterrupt in Python?
I'm writing a program that caches some results via the pickle module. What happens at the moment is that if I hit ctrl-c at while the dump operation is occurring, dump gets interrupted and the resulting file is corrupted (i.e. only partially written, so it cannot be loaded again. Is there a way to make dump, or in general a block of code, uninterruptable? My current workaround looks something like this: try: file = open(path, 'w') dump(obj, file) file.close() except KeyboardInterrupt: file.close() file.open(path,'w') dump(obj, file) file.close() raise It seems silly to restart the operation if it is interrupted, so I am searching for a way to defer the interrupt. How do I do this?
The following is a context manager that attaches a signal handler for SIGINT. If the context manager's signal handler is called, the signal is delayed by only passing the signal to the original handler when the context manager exits. import signal import logging class DelayedKeyboardInterrupt(object): def __enter__(self): self.signal_received = False self.old_handler = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, self.handler) def handler(self, sig, frame): self.signal_received = (sig, frame) logging.debug('SIGINT received. Delaying KeyboardInterrupt.') def __exit__(self, type, value, traceback): signal.signal(signal.SIGINT, self.old_handler) if self.signal_received: self.old_handler(*self.signal_received) with DelayedKeyboardInterrupt(): # stuff here will not be interrupted by SIGINT critical_code()
Using Sql Server with Django in production
Has anybody got recent experience with deploying a Django application with an SQL Server database back end? Our workplace is heavily invested in SQL Server and will not support Django if there isn't a sufficiently developed back end for it. I'm aware of mssql.django-pyodbc and django-mssql as unofficially supported back ends. Both projects seem to have only one person contributing which is a bit of a worry though the contributions seem to be somewhat regular. Are there any other back ends for SQL Server that are well supported? Are the two I mentioned here 'good enough' for production? What are your experiences?
As has been stated, django-pyodbc is a good way to go. PyODBC is probably the most mature SQL Server library for Python there is. The only thing you may have problems with is that pyodbc doesn't support stored procedures very well (you can call them, but you have no way to get results from them). You can call them using pymssql, but I would avoid it if at all possible as it doesn't support the standard DB-API interface and may be subject to changes. If you need to do this, your best bet is to use adodbapi directly (it's included with the python win32 package, which you'll probably end up installing anyway).
What's the most efficient way to find one of several substrings in Python?
I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings. To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result is 4. I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched. There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/Regex solution for this. Thanks, Rax
I would assume a regex is better than checking for each substring individually because conceptually the regular expression is modeled as a DFA, and so as the input is consumed all matches are being tested for at the same time (resulting in one scan of the input string). So, here is an example: import re def work(): to_find = re.compile("cat|fish|dog") search_str = "blah fish cat dog haha" match_obj = to_find.search(search_str) the_index = match_obj.start() # produces 5, the index of fish which_word_matched = match_obj.group() # "fish" # Note, if no match, match_obj is None UPDATE: Some care should be taken when combining words in to a single pattern of alternative words. The following code builds a regex, but escapes any regex special characters and sorts the words so that longer words get a chance to match before any shorter prefixes of the same word: def wordlist_to_regex(words): escaped = map(re.escape, words) combined = '|'.join(sorted(escaped, key=len, reverse=True)) return re.compile(combined) >>> r.search('smash atomic particles').span() (6, 10) >>> r.search('visit usenet:comp.lang.python today').span() (13, 29) >>> r.search('a north\south division').span() (2, 13) >>> r.search('012cat').span() (3, 6) >>> r.search('0123dog789cat').span() (4, 7) END UPDATE It should be noted that you will want to form the regex (ie - call to re.compile()) as little as possible. The best case would be you know ahead of time what your searches are (or you compute them once/infrequently) and then save the result of re.compile somewhere. My example is just a simple nonsense function so you can see the usage of the regex. There are some more regex docs here: http://docs.python.org/library/re.html Hope this helps. UPDATE: I am unsure about how python implements regular expressions, but to answer Rax's question about whether or not there are limitations of re.compile() (for example, how many words you can try to "|" together to match at once), and the amount of time to run compile: neither of these seem to be an issue. I tried out this code, which is good enough to convince me. (I could have made this better by adding timing and reporting results, as well as throwing the list of words into a set to ensure there are no duplicates... but both of these improvements seem like overkill). This code ran basically instantaneously, and convinced me that I am able to search for 2000 words (of size 10), and that and of them will match appropriately. Here is the code: import random import re import string import sys def main(args): words = [] letters_and_digits = "%s%s" % (string.letters, string.digits) for i in range(2000): chars = [] for j in range(10): chars.append(random.choice(letters_and_digits)) words.append(("%s"*10) % tuple(chars)) search_for = re.compile("|".join(words)) first, middle, last = words[0], words[len(words) / 2], words[-1] search_string = "%s, %s, %s" % (last, middle, first) match_obj = search_for.search(search_string) if match_obj is None: print "Ahhhg" return index = match_obj.start() which = match_obj.group() if index != 0: print "ahhhg" return if words[-1] != which: print "ahhg" return print "success!!! Generated 2000 random words, compiled re, and was able to perform matches." if __name__ == "__main__": main(sys.argv) UPDATE: It should be noted that the order of of things ORed together in the regex matters. Have a look at the following test inspired by TZOTZIOY: >>> search_str = "01catdog" >>> test1 = re.compile("cat|catdog") >>> match1 = test1.search(search_str) >>> match1.group() 'cat' >>> match1.start() 2 >>> test2 = re.compile("catdog|cat") # reverse order >>> match2 = test2.search(search_str) >>> match2.group() 'catdog' >>> match2.start() 2 This suggests the order matters :-/. I am not sure what this means for Rax's application, but at least the behavior is known. UPDATE: I posted this questions about the implementation of regular expressions in Python which will hopefully give us some insight into the issues found with this question.
How do I check if a variable exists?
I want to check if a variable exists. Now I'm doing something like this: try: myVar except NameError: # Do something. Are there other ways without exceptions?
To check the existence of a local variable: if 'myVar' in locals(): # myVar exists. To check the existence of a global variable: if 'myVar' in globals(): # myVar exists. To check if an object has an attribute: if hasattr(obj, 'attr_name'): # obj.attr_name exists.
Python: get http headers from urllib call?
does urllib fetch the whole page? when a urlopen call is made? I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call? import urllib2 myurl = 'http://bit.ly/doFeT' page = urllib2.urlopen(myurl) // open connection, get headers html = page.readlines() // stream page
What about sending a HEAD request instead of a normal GET request. The following snipped (copied from a similar question) does exactly that. >>> import httplib >>> conn = httplib.HTTPConnection("www.google.com") >>> conn.request("HEAD", "/index.html") >>> res = conn.getresponse() >>> print res.status, res.reason 200 OK >>> print res.getheaders() [('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]
Writing a __init__ function to be used in django model
I'm trying to write an __init__ function for one of my models so that I can create an object by doing p = User('name','email') When I write the model, I have def __init__(self, name, email, house_id, password): models.Model.__init__(self) self.name = name self.email = email This works, and I can save the object to the database, but when I do 'User.objects.all()', it doesn't pull anything up unless I take out my __init__ function. Any ideas?
Relying on Django's built-in functionality and passing named parameters would be the simplest way to go. p = User(name="Fred", email="fred@example.com") But if you're set on saving some keystrokes, I'd suggest adding a static convenience method to the class instead of messing with the initializer. # In User class declaration @classmethod def create(cls, name, email): return cls(name=name, email=email) # Use it p = User.create("Fred", "fred@example.com")
Profiling in Python: Who called the function?
I'm profiling in Python using cProfile. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most? EDIT: I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?
I almost always view the output of the cProfile module using Gprof2dot, basically it converts the output into a graphvis graph (a .dot file), for example: It makes it very easy to determine which function is slowest, and which function[s] called it. Usage is: python -m cProfile -o output.pstats path/to/your/script arg1 arg2 gprof2dot.py -f pstats output.pstats | dot -Tpng -o output.png
list.append or list +=?
Which is more pythonic? list.append(1) or list += [1]
list.append(1) is faster, because it doesn't create a temporary list object.
Regular expression implementation details
A question that I answered got me wondering: How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or is it subject to change? I thought that regular expressions would be implemented as DFAs, and therefore were very efficient (requiring at most one scan of the input string). Laurence Gonsalves raised an interesting point that not all Python regular expressions are regular. (His example is r"(a+)b\1", which matches some number of a's, a b, and then the same number of a's as before). This clearly cannot be implemented with a DFA. So, to reiterate: what are the implementation details and guarantees of Python regular expressions? It would also be nice if someone could give some sort of explanation (in light of the implementation) as to why the regular expressions "cat|catdog" and "catdog|cat" lead to different search results in the string "catdog", as mentioned in the question that I referenced before.
Python's re module was based on PCRE, but has moved on to their own implementation. Here is the link to the C code. It appears as though the library is based on recursive backtracking when an incorrect path has been taken. Regular expression and text size n a?nan matching an Keep in mind that this graph is not representative of normal regex searches. http://swtch.com/~rsc/regexp/regexp1.html
Performing a getattr() style lookup in a django template
Python's getattr() method is useful when you don't know the name of a certain attribute in advance. This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups?
I also had to write this code as a custom template tag recently. To handle all look-up scenarios, it first does a standard attribute look-up, then tries to do a dictionary look-up, then tries a getitem lookup (for lists to work), then follows standard Django template behavior when an object is not found. (updated 2009-08-26 to now handle list index lookups as well) # app/templatetags/getattribute.py import re from django import template from django.conf import settings numeric_test = re.compile("^\d+$") register = template.Library() def getattribute(value, arg): """Gets an attribute of an object dynamically from a string name""" if hasattr(value, str(arg)): return getattr(value, arg) elif hasattr(value, 'has_key') and value.has_key(arg): return value[arg] elif numeric_test.match(str(arg)) and len(value) > int(arg): return value[int(arg)] else: return settings.TEMPLATE_STRING_IF_INVALID register.filter('getattribute', getattribute) Template usage: {% load getattribute %} {{ object|getattribute:dynamic_string_var }}
How to get line count cheaply in Python?
I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise? At the moment I do: def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 is it possible to do any better?
One line, probably pretty fast: num_lines = sum(1 for line in open('myfile.txt'))
Emulating pass-by-value behaviour in python
I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. One possible way is to use deep copy: from copy import deepcopy def f(data): data = deepcopy(data) #do stuff is there more efficient or more pythonic way to achieve this goal, making as few assumptions as possible about the object being passed (such as .clone() method) Edit I'm aware that technically everything in python is passed by value. I was interested in emulating the behaviour, i.e. making sure I don't mess with the data that was passed to the function. I guess the most general way is to clone the object in question either with its own clone mechanism or with deepcopy.
You can make a decorator and put the cloning behaviour in that. >>> def passbyval(func): def new(*args): cargs = [deepcopy(arg) for arg in args] return func(*cargs) return new >>> @passbyval def myfunc(a): print a >>> myfunc(20) 20 This is not the most robust way, and doesn't handle key-value arguments or class methods (lack of self argument), but you get the picture. Note that the following statements are equal: @somedecorator def func1(): pass # ... same as ... def func2(): pass func2 = somedecorator(func2) You could even have the decorator take some kind of function that does the cloning and thus allowing the user of the decorator to decide the cloning strategy. In that case the decorator is probably best implemented as a class with __call__ overridden.
Concise vector adding in Python?
I often do vector addition of Python lists. Example: I have two lists like these: a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] I now want to add b to a to get the result a = [3.0, 5.0, 7.0]. Usually I end up doing like this: a[0] += b[0] a[1] += b[1] a[2] += b[2] Is there some efficient, standard way to do this with less typing? UPDATE: It can be assumed that the lists are of length 3 and contain floats.
If you need efficient vector arithmetic, try Numpy. >>> import numpy >>> a=numpy.array([0,1,2]) >>> b=numpy.array([3,4,5]) >>> a+b array([3, 5, 7]) >>> Or (thanks, Andrew Jaffe), >>> a += b >>> a array([3, 5, 7]) >>>
OOP: good class design
My question is related to this one: Python tool that builds a dependency diagram for methods of a class. After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My script generated an input file for graphviz, which was used to generate a dependency graph that looks like this. At this point I've got stuck. I've realized that I have no idea how to refactor the class to make it less complicated. I simply don't know what should I aim to. For example, in theory of relational databases there are a couple of simple rules that are used to bring a database to a normal form. What about some similar theory concerning the good class design (in terms of dependencies between its methods)? Is this topic covered somewhere so I could study it?
We follow the following principles when designing classes: The Single Responsibility Principle: A class (or method) should have only one reason to change. The Open Closed Principle: A class (or method) should be open for extension and closed for modification. The Liskov Substitution Principle: Subtypes must be substitutable for their base types. The Interface Segregation Principle: Clients should not be forced to depend upon methods that they do not use. Interfaces should belong to clients. The Dependency Inversion Principle: Abstractions should not depend on details. Details should depend on abstractions. Edit: Design patterns are helpful in getting your code to comply with these principles. I have found it very helpful to understand the principles first and then to look at the patterns and understand how the patterns bring your code in line with the principles.