instruction
stringlengths 12
148
| input
stringlengths 16
30.2k
| output
stringlengths 11
27.3k
|
|---|---|---|
How to read the header with pycurl
|
How do I read the response headers returned from a PyCurl request?
|
There are several solutions (by default, they are dropped). Here is an
example using the option HEADERFUNCTION which lets you indicate a
function to handle them.
Other solutions are options WRITEHEADER (not compatible with
WRITEFUNCTION) or setting HEADER to True so that they are transmitted
with the body.
#!/usr/bin/python
import pycurl
import sys
class Storage:
def __init__(self):
self.contents = ''
self.line = 0
def store(self, buf):
self.line = self.line + 1
self.contents = "%s%i: %s" % (self.contents, self.line, buf)
def __str__(self):
return self.contents
retrieved_body = Storage()
retrieved_headers = Storage()
c = pycurl.Curl()
c.setopt(c.URL, 'http://www.demaziere.fr/eve/')
c.setopt(c.WRITEFUNCTION, retrieved_body.store)
c.setopt(c.HEADERFUNCTION, retrieved_headers.store)
c.perform()
c.close()
print retrieved_headers
print retrieved_body
|
How to specify uniqueness for a tuple of field in a Django model
|
Is there a way to specify a Model in Django such that is ensures that pair of fields in unique in the table, in a way similar to the "unique=True" attribute for similar field?
Or do I need to check this constraint in the clean() method?
|
There is a META option called unique_together. For example:
class MyModel(models.Model):
field1 = models.BlahField()
field2 = models.FooField()
field3 = models.BazField()
class Meta:
unique_together = ("field1", "field2")
More info on the Django documentation page.
|
Binary data with pyserial(python serial port)
|
serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?
I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose a problem.
|
An alternative method, without using the array module:
def a2s(arr):
""" Array of integer byte values --> binary string
"""
return ''.join(chr(b) for b in arr)
|
Check if a given key already exists in a dictionary and increment it
|
Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?
I.e., I want to do this:
my_dict = {}
if (my_dict[key] != None):
my_dict[key] = 1
else:
my_dict[key] += 1
I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.
|
You are looking for collections.defaultdict (available for Python 2.5+). This
from collections import defaultdict
my_dict = defaultdict(int)
my_dict[key] += 1
will do what you want.
For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use
if key in my_dict:
my_dict[key] += 1
else:
my_dict[key] = 1
|
How do you create a daemon in Python?
|
Searching on Google reveals x2 code snippets. The first result is to this code recipe which has a lot of documentation and explanation, along with some useful discussion underneath.
However, another code sample, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.
These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?
|
There are many fiddly things to take care of when becoming a well-behaved daemon process:
prevent core dumps (many daemons run as root, and core dumps can contain sensitive information)
behave correctly inside a chroot gaol
set UID, GID, working directory, umask, and other process parameters appropriately for the use case
relinquish elevated suid, sgid privileges
close all open file descriptors, with exclusions depending on the use case
behave correctly if started inside an already-detached context, such as init, inetd, etc.
set up signal handlers for sensible daemon behaviour, but also with specific handlers determined by the use case
redirect the standard streams stdin, stdout, stderr since a daemon process no longer has a controlling terminal
handle a PID file as a cooperative advisory lock, which is a whole can of worms in itself with many contradictory but valid ways to behave
allow proper cleanup when the process is terminated
actually become a daemon process without leading to zombies
Some of these are standard, as described in canonical Unix literature (Advanced Programming in the UNIX Environment, by the late W. Richard Stevens, Addison-Wesley, 1992). Others, such as stream redirection and PID file handling, are conventional behaviour most daemon users would expect but that are less standardised.
All of these are covered by the PEP 3143 âStandard daemon process libraryâ specification. The python-daemon reference implementation works on Python 2.7 or later, and Python 3.2 or later.
|
Shuffle an array with python, randomize array item order with python
|
What's the easiest way to shuffle an array with python?
|
import random
random.shuffle(array)
|
What is the best way to repeatedly execute a function every x seconds in Python?
|
I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.
In this question about a cron implemented in Python, the solution appears to effectively just sleep() for x seconds. I don't need such advanced functionality so perhaps something like this would work
while True:
# Code executed here
time.sleep(60)
Are there any foreseeable problems with this code?
|
Use the sched module, which implements a general purpose event scheduler.
import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print "Doing stuff..."
# do your stuff
s.enter(60, 1, do_something, (sc,))
s.enter(60, 1, do_something, (s,))
s.run()
|
Python - why use "self" in a class?
|
How do these 2 classes differ?
class A():
x=3
class B():
def __init__(self):
self.x=3
Is there any significant difference?
|
A.x is a class variable.
B's self.x is an instance variable.
i.e. A's x is shared between instances.
It would be easier to demonstrate the difference with something that can be modified like a list:
#!/usr/bin/env python
class A:
x = []
def add(self):
self.x.append(1)
class B:
def __init__(self):
self.x = []
def add(self):
self.x.append(1)
x = A()
y = A()
x.add()
y.add()
print "A's x:",x.x
x = B()
y = B()
x.add()
y.add()
print "B's x:",x.x
Output
A's x: [1, 1]
B's x: [1]
|
Order a QuerySet by aggregate field value
|
Let's say I have the following model:
class Contest:
title = models.CharField( max_length = 200 )
description = models.TextField()
class Image:
title = models.CharField( max_length = 200 )
description = models.TextField()
contest = models.ForeignKey( Contest )
user = models.ForeignKey( User )
def score( self ):
return self.vote_set.all().aggregate( models.Sum( 'value' ) )[ 'value__sum' ]
class Vote:
value = models.SmallIntegerField()
user = models.ForeignKey( User )
image = models.ForeignKey( Image )
The users of a site can contribute their images to several contests. Then other users can vote them up or down.
Everything works fine, but now I want to display a page on which users can see all contributions to a certain contest. The images shall be ordered by their score.
Therefore I tried the following:
Contest.objects.get( pk = id ).image_set.order_by( 'score' )
As I feared it doesn't work since 'score' is no database field that could be used in queries.
|
Oh, of course I forget about new aggregation support in Django and its annotate functionality.
So query may look like this:
Contest.objects.get(pk=id).image_set.annotate(score=Sum('vote__value')).order_by( 'score' )
|
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
|
How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?
I know I can do an MD5 checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?
|
The exact same question that people at the old AudioScrobbler and currently at MusicBrainz have worked on since long ago. For the time being, the Python project that can aid in your quest, is Picard, which will tag audio files (not only MPEG 1 Layer 3 files) with a GUID (actually, several of them), and from then on, matching the tags is quite simple.
If you prefer to do it as a project of your own, libofa might be of help.
|
Resolving a relative url path to its absolute path
|
Is there a library in python that works like this?
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
'http://www.asite.com/folder/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html")
'http://www.asite.com/folder/folder2/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html")
'http://www.asite.com/folder3/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "../finalpage.html")
'http://www.asite.com/finalpage.html'
|
Yes, there is urlparse.urljoin, or urllib.parse.urljoin for Python 3.
>>> try: from urlparse import urljoin # Python2
... except ImportError: from urllib.parse import urljoin # Python3
...
>>> urljoin("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
'http://www.asite.com/folder/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html")
'http://www.asite.com/folder/folder2/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html")
'http://www.asite.com/folder3/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "../finalpage.html")
'http://www.asite.com/finalpage.html'
for copy-and-paste:
try:
from urlparse import urljoin # Python2
except ImportError:
from urllib.parse import urljoin # Python3
|
Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages?
|
I recently discovered metaclasses in python.
Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, etc. All of this becomes not only possible but simple.
But in python, metaclasses are also plain classes. So, I started wondering if the abstraction could usefully go higher, and it seems to me that it can and that:
a metaclass corresponds to or implements a role in a pattern (as in GOF pattern languages).
a meta-metaclass is the pattern itself (if we allow it to create tuples of classes representing abstract roles, rather than just a single class)
a meta-meta-metaclass is a pattern factory, which corresponds to the GOF pattern groupings, e.g. Creational, Structural, Behavioural. A factory where you could describe a case of a certain type of problem and it would give you a set of classes that solved it.
a meta-meta-meta-metaclass (as far as I could go), is a pattern factory factory, a factory to which you could perhaps describe the type of your problem and it would give you a pattern factory to ask.
I have found some stuff about this online, but mostly not very useful. One problem is that different languages define metaclasses slightly differently.
Has anyone else used metaclasses like this in python/elsewhere, or seen this used in the wild, or thought about it? What are the analogues in other languages? E.g. in C++ how deep can the template recursion go?
I'd very much like to research it further.
|
This reminds me of the eternal quest some people seem to be on to make a "generic implementation of a pattern." Like a factory that can create any object (including another factory), or a general-purpose dependency injection framework that is far more complex to manage than simply writing code that actually does something.
I had to deal with people intent on abstraction to the point of navel-gazing when I was managing the Zend Framework project. I turned down a bunch of proposals to create components that didn't do anything, they were just magical implementations of GoF patterns, as though the pattern were a goal in itself, instead of a means to a goal.
There's a point of diminishing returns for abstraction. Some abstraction is great, but eventually you need to write code that does something useful.
Otherwise it's just turtles all the way down.
|
Resources for TDD aimed at Python Web Development
|
I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.
Are there any particular ones you would recommend for this language/application?
|
I wrote a series of blogs on TDD in Django that covers some TDD with the nose testing framework.
There are a lot of free online resources out there for learning about TDD:
The c2 wiki article gives good background on general TDD philosophy.
The onlamp article is a simple introduction.
Here's a presentation on TDD with game development in pygame that really helped me understand TDD.
For testing web applications, test first or otherwise, I'd recommend twill and selenium as tools to use.
|
Using a java library from python
|
I have a python app and java app. The python app generates input for the java app and invokes it on the command line.
I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java.
Any pointers?
(FYI I'm v. new to Python)
Clarification (at the cost of a long question: apologies)
The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app.
So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM).
Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.
|
Sorry to ressurect the thread, but there was no accepted answer...
You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:
>>> from py4j.java_gateway import JavaGateway
>>> gateway = JavaGateway() # connect to the JVM
>>> java_object = gateway.jvm.mypackage.MyClass() # invoke constructor
>>> other_object = java_object.doThat()
>>> other_object.doThis(1,'abc')
>>> gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method
As opposed to Jython, Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The communication is done through sockets instead of JNI.
Disclaimer: I am the author of Py4J
|
How to read Unicode input and compare Unicode strings in Python?
|
I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of raw_input?
Also, I would like to test Unicode strings for equality and it looks like a standard == does not work.
Thank you for your help !
|
raw_input() returns strings as encoded by the OS or UI facilities. The difficulty is knowing which is that decoding. You might attempt the following:
import sys, locale
text= raw_input().decode(sys.stdin.encoding or locale.getpreferredencoding(True))
which should work correctly in most of the cases.
We need more data about not working Unicode comparisons in order to help you. However, it might be a matter of normalization. Consider the following:
>>> a1= u'\xeatre'
>>> a2= u'e\u0302tre'
a1 and a2 are equivalent but not equal:
>>> print a1, a2
être être
>>> print a1 == a2
False
So you might want to use the unicodedata.normalize() method:
>>> import unicodedata as ud
>>> ud.normalize('NFC', a1)
u'\xeatre'
>>> ud.normalize('NFC', a2)
u'\xeatre'
>>> ud.normalize('NFC', a1) == ud.normalize('NFC', a2)
True
If you give us more information, we might be able to help you more, though.
|
Python import coding style
|
I've discovered a new pattern. Is this pattern well known or what is the opinion about it?
Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of
import foo
from bar.baz import quux
def myFunction():
foo.this.that(quux)
I move all my imports into the function where they're actually used., like this:
def myFunction():
import foo
from bar.baz import quux
foo.this.that(quux)
This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.
Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.
|
The (previously) top-voted answer to this question is nicely formatted but absolutely wrong about performance. Let me demonstrate
Performance
Top Import
import random
def f():
L = []
for i in xrange(1000):
L.append(random.random())
for i in xrange(1000):
f()
$ time python import.py
real 0m0.721s
user 0m0.412s
sys 0m0.020s
Import in Function Body
def f():
import random
L = []
for i in xrange(1000):
L.append(random.random())
for i in xrange(1000):
f()
$ time python import2.py
real 0m0.661s
user 0m0.404s
sys 0m0.008s
As you can see, it can be more efficient to import the module in the function. The reason for this is simple. It moves the reference from a global reference to a local reference. This means that, for CPython at least, the compiler will emit LOAD_FAST instructions instead of LOAD_GLOBAL instructions. These are, as the name implies, faster. The other answerer artificially inflated the performance hit of looking in sys.modules by importing on every single iteration of the loop.
As a rule, it's best to import at the top but performance is not the reason if you are accessing the module a lot of times. The reasons are that one can keep track of what a module depends on more easily and that doing so is consistent with most of the rest of the Python universe.
|
How do I simulate flip of biased coin in python?
|
In unbiased coin flip H or T occurs 50% of times.
But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'.
something like this:
def flip(p):
'''this function return H with probability p'''
# do something
return result
>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]
|
random.random() returns a uniformly distributed pseudo-random floating point number in the range [0, 1). This number is less than a given number p in the range [0,1) with probability p. Thus:
def flip(p):
return 'H' if random.random() < p else 'T'
Some experiments:
>>> N = 100
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.17999999999999999 # Approximately 20% of the coins are heads
>>> N = 10000
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.20549999999999999 # Better approximation
|
Python decimal range() step value
|
Is there a way to step between 0 and 1 by 0.1?
I thought I could do it like the following, but it failed:
for i in range(0, 1, 0.1):
print i
Instead, it says that the step argument cannot be zero, which I did not expect.
|
You can also use the NumPy library (which isn't part of standard library but is relatively easy to obtain) which has the arange function:
>>> import numpy as np
>>> np.arange(0,1,0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
as well as the linspace function which lets you have control over what happens at the endpoint (non-trivial for floating point numbers when things won't always divide into the correct number of "slices"):
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
|
Easy_install of wxpython has "setup script" error
|
I have an install of python 2.5 that fink placed in /sw/bin/. I use the easy install command
sudo /sw/bin/easy_install wxPython
to try to install wxpython and I get an error while trying to process wxPython-src-2.8.9.1.tab.bz2 that there is not setup script. Easy-install has worked for several other installations until this one. Any help on why it's busting now?
EDIT: The error occurs before dumping back to shell prompt.
Reading http://wxPython.org/download.php
Best match: wxPython src-2.8.9.1
Downloading http://downloads.sourceforge.net/wxpython/wxPython-src-2.8.9.1.tar.bz2
Processing wxPython-src-2.8.9.1.tar.bz2
error: Couldn't find a setup script in /tmp/easy_install-tNg6FG/wxPython-src-2.8.9.1.tar.bz2
|
There is a simple reason why it's busting: there just is no setup.py in wxPython; wxPython does not use distutils for installation.
Instead, read the file README.1st.txt in source distribution for instruction on how to install wxPython.
|
What's the idiomatic Python equivalent to Django's 'regroup' template tag?
|
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
I can think of a few ways of doing it with loops but I'd particularly like to know if there is a neat one-liner.
|
Combine itertools.groupby with operator.itemgetter to get a pretty nice solution:
from operator import itemgetter
from itertools import groupby
key = itemgetter('gender')
iter = groupby(sorted(people, key=key), key=key)
for gender, people in iter:
print '===', gender, '==='
for person in people:
print person
|
How to send multiple input field values with same name?
|
I have m2m field, lets say it have name 'relations', so i want to allow user to send as many relations as he wants. I add new input to html with javascript with same name, like so
<input type='text' name='relations' value='a' />
<input type='text' name='relations' value='b' />
in cleaned_data i receive only value of second input ('b'). How to receive both?
|
I don't know how to do that with Forms, but if you want to grab the values in the raw way, here's how I'd do:
relations = request.POST.getlist('relations')
|
Python regular expressions with more than 100 groups?
|
Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.
|
There is a limit because it would take too much memory to store the complete state machine efficiently. I'd say that if you have more than 100 groups in your re, something is wrong either in the re itself or in the way you are using them. Maybe you need to split the input and work on smaller chunks or something.
|
How do you remove duplicates from a list in whilst preserving order?
|
Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:
def uniq(input):
output = []
for x in input:
if x not in output:
output.append(x)
return output
(Thanks to unwind for that code sample.)
But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.
Related question: In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique while preserving order?
|
Here you have some alternatives: http://www.peterbe.com/plog/uniqifiers-benchmark
Fastest one:
def f7(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
Why assign seen.add to seen_add instead of just calling seen.add? Python is a dynamic language, and resolving seen.add each iteration is more costly than resolving a local variable. seen.add could have changed between iterations, and the runtime isn't smart enough to rule that out. To play it safe, it has to check the object each time.
If you plan on using this function a lot on the same dataset, perhaps you would be better off with an ordered set: http://code.activestate.com/recipes/528878/
O(1) insertion, deletion and member-check per operation.
|
Get the title of the current active Window/Document in Mac OS X
|
Refering to a previously asked question, I would like to know how to get the title of the current active document.
I tried the script mention in the answers to the question above. This works, but only gives me the name of the application. For example, I am writing this question: When I fire up the script it gives me the name of the application, i.e. "Firefox". This is pretty neat, but does not really help. I would rather like to capture the title of my current active document. See the image.
I am using Leopard, so no backward compatibility needed. Also I am using Python's Appkit to gain access to the NSWorkspace class, but if you tell me the Objective-C code, I could figure out the translation to Python.
Ok, I've got a solution which is not very satisfing, thats why I don't mark Koen Bok's answer. At least not yet.
tell application "System Events"
set frontApp to name of first application process whose frontmost is true
end tell
tell application frontApp
if the (count of windows) is not 0 then
set window_name to name of front window
end if
end tell
Save as script and invoke it with osascript from the shell.
|
As far as I know your best bet is wrapping an AppleScript. But AppleScript is magic to me so I leave it as an exercise for the questioner :-)
This might help a little: http://www.macosxhints.com/article.php?story=20060105082728937&lsrc=osxh
|
Can a lambda function call itself recursively in Python?
|
A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?
|
The only way I can think of to do this amounts to giving the function a name:
fact = lambda x: 1 if x == 0 else x * fact(x-1)
or alternately, for earlier versions of python:
fact = lambda x: x == 0 and 1 or x * fact(x-1)
Update: using the ideas from the other answers, I was able to wedge the factorial function into a single unnamed lambda:
>>> map(lambda n: (lambda f, *a: f(f, *a))(lambda rec, n: 1 if n == 0 else n*rec(rec, n-1), n), range(10))
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
So it's possible, but not really recommended!
|
How would you do the equivalent of preprocessor directives in Python?
|
Is there a way to do the following preprocessor directives in Python?
#if DEBUG
< do some code >
#else
< do some other code >
#endif
|
There's __debug__, which is a special value that the compiler does preprocess.
if __debug__:
print "If this prints, you're not running python -O."
else:
print "If this prints, you are running python -O!"
__debug__ will be replaced with a constant 0 or 1 by the compiler, and the optimizer will remove any if 0: lines before your source is interpreted.
|
How do I convert a string to a double in Python?
|
I would like to know how to convert a string containing digits to a double.
|
>>> x = "2342.34"
>>> float(x)
2342.3400000000001
There you go. Use float (which is almost always a C double).
|
Python reverse / invert a mapping
|
Given a dictionary like so:
my_map = { 'a': 1, 'b':2 }
How can one invert this map to get:
inv_map = { 1: 'a', 2: 'b' }
EDITOR NOTE: map changed to my_map to avoid conflicts with the built-in function, map. Some comments may be affected below.
|
For Python 2.7.x
inv_map = {v: k for k, v in my_map.iteritems()}
For Python 3+:
inv_map = {v: k for k, v in my_map.items()}
|
Why do I get TypeError: can't multiply sequence by non-int of type 'float'?
|
I am typing to get a sale amount (by input) to be multiplied by a defined sales tax (0.08) and then have it print the total amount (sales tax times sale amount).
I run into this error. Anyone know what could be wrong or have any suggestions?
salesAmount = raw_input (["Insert sale amount here \n"])
['Insert sale amount here \n']20.99
>>> salesTax = 0.08
>>> totalAmount = salesAmount * salesTax
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
totalAmount = salesAmount * salesTax
TypeError: can't multiply sequence by non-int of type 'float'
|
raw_input returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3 is "ABABAB"; how much is "L" * 3.14 ? Please do not reply "LLL|"). You need to parse the string to a numerical value.
You might want to try:
salesAmount = float(raw_input("Insert sale amount here\n"))
|
Ruby equivalent of virtualenv?
|
Is there something similar to the Python utility virtualenv?
Basically it allows you to install Python packages into a sandboxed environment, so easy_install django doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory.
For example:
$ virtualenv test
New python executable in test/bin/python
Installing setuptools...cd .........done.
$ cd test/
$ source bin/activate
(test)$ easy_install tvnamer
Searching for tvnamer
Best match: tvnamer 0.5.1
Processing tvnamer-0.5.1-py2.5.egg
Adding tvnamer 0.5.1 to easy-install.pth file
Installing tvnamer script to /Users/dbr/test/bin
Using /Library/Python/2.5/site-packages/tvnamer-0.5.1-py2.5.egg
Processing dependencies for tvnamer
Finished processing dependencies for tvnamer
(test)$ which tvnamer
/Users/dbr/test/bin/tvnamer
Is there something like this for RubyGems?
|
RVM works closer to how virtualenv works since it lets you sandbox different ruby versions and their gems, etc.
|
How do I specify input and output data types in python comments?
|
I have seen several standards for writing comments about the kind of data a function expects and returns in Python. Is there a consensus on which one is best-practice?
Is the new functionality in http://www.python.org/dev/peps/pep-3107/ something I should start using for this?
|
Function annotations are not for a specific use, they can be used for anything.
Tools can be written to extract information from the annotations and do anything you want, including checking types or generating documentation. But python itself does not do anything with the information. You could use to a completely different purpose, i.e. to provide a function that will be called on the parameter or to declare a string of possible return values.
Annotations can be any object:
def somefunc(param1: "string annotation",
param2: 151631,
param3: any_object): -> "some information here":
and you can retrieve the objects using:
print (somefunc.func_annotations)
{'param1': "string annotation",
'param2': 151631,
'param3': <object any_object>,
'return': "some information here"}
Use case suggestions provided by the PEP:
Providing typing information
Type checking
Let IDEs show what types a function expects and returns
Function overloading / generic functions
Foreign-language bridges
Adaptation
Predicate logic functions
Database query mapping
RPC parameter marshaling
Other information
Documentation for parameters and return values
Since function annotation syntax is too new, it is really not used for any production tools.
I suggest using other methods to document that. I use epydoc to generate my documentation, and it can read parameter typing information from docstrings:
def x_intercept(m, b):
"""
Return the x intercept of the line M{y=m*x+b}. The X{x intercept}
of a line is the point at which it crosses the x axis (M{y=0}).
This function can be used in conjuction with L{z_transform} to
find an arbitrary function's zeros.
@type m: number
@param m: The slope of the line.
@type b: number
@param b: The y intercept of the line. The X{y intercept} of a
line is the point at which it crosses the y axis (M{x=0}).
@rtype: number
@return: the x intercept of the line M{y=m*x+b}.
"""
return -b/m
This example is from epydoc's website. It can generate documentation in a variety of formats, and can generate good graphs from your classes and call profiles.
|
Reducing Django Memory Usage. Low hanging fruit?
|
My memory usage increases over time and restarting Django is not kind to users.
I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.
I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.
Can anyone suggest others? How much improvement would caching on low-traffic sites?
In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.
Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?
Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction.
Edit: Carl posted a slightly more detailed reply here that is worth reading: http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead
Edit: Graham Dumpleton's article is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though.
Final Edit: Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:
"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."
So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.
Thanks for everyone's assistance but I think this question is still open!
Another final edit ;-)
I asked this on the django-users list and got some very helpful replies
Honestly the last update ever!
This was just released. Could be the best solution yet: Profiling Django object size and memory usage with Pympler
|
Make sure you are not keeping global references to data. That prevents the python garbage collector from releasing the memory.
Don't use mod_python. It loads an interpreter inside apache. If you need to use apache, use mod_wsgi instead. It is not tricky to switch. It is very easy. mod_wsgi is way easier to configure for django than brain-dead mod_python.
If you can remove apache from your requirements, that would be even better to your memory. spawning seems to be the new fast scalable way to run python web applications.
EDIT: I don't see how switching to mod_wsgi could be "tricky". It should be a very easy task. Please elaborate on the problem you are having with the switch.
|
Is there a standard way to list names of Python modules in a package?
|
Is there a straightforward way to list the names of all modules in a package, without using __all__?
For example, given this package:
/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py
I'm wondering if there is a standard or built-in way to do something like this:
>>> package_contents("testpkg")
['modulea', 'moduleb']
The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?
|
Using python2.3 and above, you could also use the pkgutil module:
>>> import pkgutil
>>> [name for _, name, _ in pkgutil.iter_modules(['testpkg'])]
['modulea', 'moduleb']
EDIT: Note that the parameter is not a list of modules, but a list of paths, so you might want to do something like this:
>>> import os.path, pkgutil
>>> import testpkg
>>> pkgpath = os.path.dirname(testpkg.__file__)
>>> print [name for _, name, _ in pkgutil.iter_modules([pkgpath])]
|
Django: ModelMultipleChoiceField doesn't select initial choices
|
ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example:
http://code.djangoproject.com/ticket/5247#comment:6
My models and form:
class Company(models.Model):
company_name = models.CharField(max_length=200)
class Contact(models.Model):
company = models.ForeignKey(Company)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Action(models.Model):
company = models.ForeignKey(Company, blank=True, null=True)
from_company = models.ManyToManyField(Contact, verbose_name='Participant(s) from "Company"', blank=True, null=True)
class Action_Form(ModelForm):
from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.none(), widget=forms.CheckboxSelectMultiple())
class Meta:
model = Action
What I do and the results:
>>> contacts_from_company = Contact.objects.filter(company__exact=1) # "1" for test, otherwise a variable
>>> form = Action_Form(initial={'from_company': [o.pk for o in contacts_from_company]}) # as suggested in the fix
>>> print form['from_company']
<ul>
</ul>
>>> print contacts_from_company
[<Contact: test person>, <Contact: another person>]
>>> form2 = Action_Form(initial={'from_company': contacts_from_company})
>>> print form2['from_company']
<ul>
</ul>
>>> form3 = Action_Form(initial={'from_company': Contact.objects.all()})
>>> print form3['from_company']
<ul>
</ul>
The way I was hoping it would work:
1. My view gets "company" from request.GET
2. It then filters all "contacts" for that "company"
3. Finally, it creates a form and passes those "contacts" as "initial={...}"
Two questions:
1. [not answered yet] How can I make ModelMultipleChoiceField take those "initial" values?
2. [answered] As an alternative, can I pass a variable to Action_Form(ModelForm) so that in my ModelForm I could have:
from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(company__exact=some_id) # where some_id comes from a view
|
I'm replying for 1)
1. How can I make ModelMultipleChoiceField take those "initial" values?
This could be done in your Action_Form __init__ method using ModelMultipleChoiceField initial attribute.
As it says in the Django source code (db/models/fields/related.py)
in def formfield(self, **kwargs):
# If initial is passed in, it's a list of related objects, but the
# MultipleChoiceField takes a list of IDs.
So you need to give it a list of IDs:
class Action_Form(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(Action_Form, self).__init__(*args, **kwargs)
self.fields['from_company'].initial = [c.pk for c in Contact.object.filter()]
|
calculate exponential moving average in python
|
I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this?
I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place.
So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates?
from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
(there's probably a better way to structure the data, any advice would be appreciated)
|
EDIT:
It seems that mov_average_expw() function from scikits.timeseries.lib.moving_funcs submodule from SciKits (add-on toolkits that complement SciPy) better suits the wording of your question.
To calculate an exponential smoothing of your data with a smoothing factor alpha (it is (1 - alpha) in Wikipedia's terms):
>>> alpha = 0.5
>>> assert 0 < alpha <= 1.0
>>> av = sum(alpha**n.days * iq
... for n, iq in map(lambda (day, iq), today=max(days): (today-day, iq),
... sorted(zip(days, IQ), key=lambda p: p[0], reverse=True)))
95.0
The above is not pretty, so let's refactor it a bit:
from collections import namedtuple
from operator import itemgetter
def smooth(iq_data, alpha=1, today=None):
"""Perform exponential smoothing with factor `alpha`.
Time period is a day.
Each time period the value of `iq` drops `alpha` times.
The most recent data is the most valuable one.
"""
assert 0 < alpha <= 1
if alpha == 1: # no smoothing
return sum(map(itemgetter(1), iq_data))
if today is None:
today = max(map(itemgetter(0), iq_data))
return sum(alpha**((today - date).days) * iq for date, iq in iq_data)
IQData = namedtuple("IQData", "date iq")
if __name__ == "__main__":
from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
iqdata = list(map(IQData, days, IQ))
print("\n".join(map(str, iqdata)))
print(smooth(iqdata, alpha=0.5))
Example:
$ python26 smooth.py
IQData(date=datetime.date(2008, 1, 1), iq=110)
IQData(date=datetime.date(2008, 1, 2), iq=105)
IQData(date=datetime.date(2008, 1, 7), iq=90)
95.0
|
Python super() raises TypeError
|
In Python 2.5.2, the following code raises a TypeError:
>>> class X:
... def a(self):
... print "a"
...
>>> class Y(X):
... def a(self):
... super(Y,self).a()
... print "b"
...
>>> c = Y()
>>> c.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in a
TypeError: super() argument 1 must be type, not classobj
If I replace the class X with class X(object), it will work. What's the explanation for this?
|
The reason is that super() only operates on new-style classes, which in the 2.x series means extending from object.
|
Why am I getting the following error in Python "ImportError: No module named py"?
|
I'm a Python newbie, so bear with me :)
I created a file called test.py with the contents as follows:
test.py
import sys
print sys.platform
print 2 ** 100
I then ran import test.py file in the interpreter to follow an example in my book.
When I do this, I get the output with the import error on the end.
win32
1267650600228229401496703205376
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named py
Why do I get this error and how do I fix it? Thanks!
|
Instead of:
import test.py
simply write:
import test
This assumes test.py is in the same directory as the file that imports it.
|
Locking a file in Python
|
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
|
Alright, so I ended up going with the code I wrote here, on my website (also available on GitHub). I can use it in the following fashion:
from filelock import FileLock
with FileLock("myfile.txt"):
# work with the file as it is now locked
print("Lock acquired.")
|
Convert list of ints to one number?
|
I have a list of integers that I would like to convert to one number like:
numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
What is the best way to implement the magic function?
EDIT
I did find this, but it seems like there has to be a better way.
|
# Over-explaining a bit:
def magic(numList): # [1,2,3]
s = map(str, numList) # ['1','2','3']
s = ''.join(s) # '123'
s = int(s) # 123
return s
# How I'd probably write it:
def magic(numList):
s = ''.join(map(str, numList))
return int(s)
# As a one-liner
num = int(''.join(map(str,numList)))
# Functionally:
s = reduce(lambda x,y: x+str(y), numList, '')
num = int(s)
# Using some oft-forgotten built-ins:
s = filter(str.isdigit, repr(numList))
num = int(s)
|
split a multi-page pdf file into multiple pdf files with python?
|
I'd like to take a multi-page pdf file and create separate pdf files per page.
I've downloaded reportlab and have browsed the documentation, but it seems aimed at pdf generation, I haven't yet seen anything about processing pdf's themselves.
Is there an easy way to do this in python?
|
pyPdf can handle this nicely (c.f. http://pybrary.net/pyPdf/ )
from pyPdf import PdfFileWriter, PdfFileReader
inputpdf = PdfFileReader(open("document.pdf", "rb"))
for i in xrange(inputpdf.numPages):
output = PdfFileWriter()
output.addPage(inputpdf.getPage(i))
with open("document-page%s.pdf" % i, "wb") as outputStream:
output.write(outputStream)
etc.
|
django-cart or Satchmo?
|
I'm looking to implement a very basic shopping cart. Satchmo seems to install a lot of applications and extra stuff that I don't need. I've heard others mention django-cart. Has anyone tried this Django app (django-cart)? Anything to watch for or any other experiences?
|
Well if you want to use django-cart you should view it as a starting point for developing your own. The last commit (r4) for the project was November 2006.
By comparison, the last commit (r1922) to Satchmo was a couple of hours ago.
With Satchmo you get code that is under active development and actually used by real e-commerce sites.
If you develop your own you're running the risk of alienating customers and losing money. If you use Satchmo you can spend more time developing/improving other areas of your site.
I bet you can already guess my recommendation :)
As for the apps and other stuff in Satchmo I can tell you, from personal experience, that you don't need to include them all in your INSTALLED_APPS setting. I don't remember exactly what I pared it down to, but there were only around 6-7 Satchmo apps in my INSTALLED_APPS and they were all ones I needed. I think they've done even more modularization since then.
|
Regex replace (in Python) - a simpler way?
|
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like:
"(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)"
And then concatenate the start group with the new data for replace and then the end group.
Is there a better method for this?
|
>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:
sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used.
|
No code completion and syntax highlighting in Pydev
|
I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?
Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program.
I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.
If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion
|
To enable code completion, go to Window > Preferences > Pydev > Editor > Code Completion, and check the 'Use Code Completion?' box, as well as the other boxes for what you want to complete on. It seems to take a second to load, the first time it has to complete something.
Syntax coloring should just work by default. Right-click on the file in the package explorer, go to 'Open With', and make sure you're opening it with the Python Editor, and not the regular Text Editor.
I don't know exactly what you mean by importing external modules. I have my source in a separate directory structure on disk; my PyDev projects contain folders linked to those. Code completion works for that, as well as other modules like 'os'. If you're having troubles, are the modules added to the PyDev's Python search path (not necessarily the same as the regular one)?
I took a brief look at Komodo and Wingware a while back, so I can't answer the second part of your question. But ended up going with PyDev. I'm not a big fan of Eclipse, but PyDev works reasonably well for me.
|
Unicode (utf8) reading and writing to files in python
|
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).
# the string, which has an a-acute in it.
ss = u'Capit\xe1n'
ss8 = ss.encode('utf8')
repr(ss), repr(ss8)
("u'Capit\xe1n'", "'Capit\xc3\xa1n'")
print ss, ss8
print >> open('f1','w'), ss8
>>> file('f1').read()
'Capit\xc3\xa1n\n'
So I type in Capit\xc3\xa1n into my favorite editor, in file f2.
then:
>>> open('f1').read()
'Capit\xc3\xa1n\n'
>>> open('f2').read()
'Capit\\xc3\\xa1n\n'
>>> open('f1').read().decode('utf8')
u'Capit\xe1n\n'
>>> open('f2').read().decode('utf8')
u'Capit\\xc3\\xa1n\n'
What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.
Edit: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?
>>> print simplejson.dumps(ss)
'"Capit\u00e1n"'
>>> print >> file('f3','w'), simplejson.dumps(ss)
>>> simplejson.load(open('f3'))
u'Capit\xe1n'
|
Rather than mess with the encode, decode methods I find it easier to use the open method from the codecs module.
>>>import codecs
>>>f = codecs.open("test", "r", "utf-8")
Then after calling f's read() function, an encoded unicode object is returned.
>>>f.read()
u'Capit\xe1l\n\n'
If you know the encoding of a file, using the codecs package is going to be much less confusing.
See http://docs.python.org/library/codecs.html#codecs.open
|
IndentationError: unindent does not match any outer indentation level
|
When I compile the Python code below, I get
IndentationError: unindent does not match any outer indentation level
import sys
def Factorial(n): # Return factorial
result = 0
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
Why?
|
EDIT: Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search&replace to replace all tabs with a few spaces.
Try this:
import sys
def Factorial(n): # return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
print Factorial(10)
|
Setting the correct encoding when piping stdout in Python
|
When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:
# -*- coding: utf-8 -*-
print u"åäö"
will work fine when run normally, but fail with:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)
when used in a pipe sequence.
What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using?
The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print u"åäö"
Is there a better way to make piping work?
|
First, regarding this solution:
# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')
It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.
A better solution is to change sys.stdout at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by "toka":
import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
|
Timeout on a function call
|
I'm calling a function in Python which I know may stall and force me to restart the script.
How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
|
You may use the signal package if you are running on UNIX:
In [1]: import signal
# Register an handler for the timeout
In [2]: def handler(signum, frame):
...: print "Forever is over!"
...: raise Exception("end of time")
...:
# This function *may* run for an indetermined time...
In [3]: def loop_forever():
...: import time
...: while 1:
...: print "sec"
...: time.sleep(1)
...:
...:
# Register the signal function handler
In [4]: signal.signal(signal.SIGALRM, handler)
Out[4]: 0
# Define a timeout for your function
In [5]: signal.alarm(10)
Out[5]: 0
In [6]: try:
...: loop_forever()
...: except Exception, exc:
...: print exc
....:
sec
sec
sec
sec
sec
sec
sec
sec
Forever is over!
end of time
# Cancel the timer if the function returned before timeout
# (ok, mine won't but yours maybe will :)
In [7]: signal.alarm(0)
Out[7]: 0
10 seconds after the call alarm.alarm(10), the handler is called. This raises an exception that you can intercept from the regular Python code.
This module doesn't play well with threads (but then, who does?)
Note that since we raise an exception when timeout happens, it may end up caught and ignored inside the function, for example of one such function:
def loop_forever():
while 1:
print 'sec'
try:
time.sleep(10)
except:
continue
|
Reversing a regular expression in Python
|
I want to reverse a regular expression. I.e. given a regular expression, I want to produce any string that will match that regex.
I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)
I'm using Python, so I'd like a Python library.
To reiterate, I only want one string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.
I'm willing for this library to only work on a certain subset of regex.
|
Somebody else had a similar (duplicate?) question here, and I'd like to offer a little helper library for generating random strings with Python that I've been working on.
It includes a method, xeger() that allows you to create a string from a regex:
>>> import rstr
>>> rstr.xeger(r'[A-Z]\d[A-Z] \d[A-Z]\d')
u'M5R 2W4'
Right now, it works with most basic regular expressions, but I'm sure it could be improved.
|
Is there a way to convert number words to Integers?
|
I need to convert one into 1, two into 2 and so on.
Is there a way to do this with a library or a class or anything?
|
The majority of this code is to set up the numwords dict, which is only done on the first call.
def text2int(textnum, numwords={}):
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion"]
numwords["and"] = (1, 0)
for idx, word in enumerate(units): numwords[word] = (1, idx)
for idx, word in enumerate(tens): numwords[word] = (1, idx * 10)
for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0)
current = result = 0
for word in textnum.split():
if word not in numwords:
raise Exception("Illegal word: " + word)
scale, increment = numwords[word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
return result + current
print text2int("seven billion one hundred million thirty one thousand three hundred thirty seven")
#7100031337
|
In Django, how do you retrieve data from extra fields on many-to-many relationships without an explicit query for it?
|
Given a situation in Django 1.0 where you have extra data on a Many-to-Many relationship:
class Player(models.Model):
name = models.CharField(max_length=80)
class Team(models.Model):
name = models.CharField(max_length=40)
players = models.ManyToManyField(Player, through='TeamPlayer', related_name='teams')
class TeamPlayer(models.Model):
player = models.ForeignKey(Player)
team = models.ForeignKey(Team)
captain = models.BooleanField()
The many-to-many relationship allows you to access the related data using attributes (the "players" attribute on the Team object or using the "teams" attribute on the Player object by way of its related name). When one of the objects is placed into a context for a template (e.g. a Team placed into a Context for rendering a template that generates the Team's roster), the related objects can be accessed (i.e. the players on the teams), but how can the extra data (e.g. 'captain') be accessed along with the related objects from the object in context (e.g.the Team) without adding additional data into the context?
I know it is possible to query directly against the intermediary table to get the extra data. For example:
TeamPlayer.objects.get(player=790, team=168).captain
Or:
for x in TeamPlayer.objects.filter(team=168):
if x.captain:
print "%s (Captain)" % (x.player.name)
else:
print x.player.name
Doing this directly on the intermediary table, however requires me to place additional data in a template's context (the result of the query on TeamPlayer) which I am trying to avoid if such a thing is possible.
|
So, 15 minutes after asking the question, and I found my own answer.
Using dir(Team), I can see another generated attribute named teamplayer_set (it also exists on Player).
t = Team.objects.get(pk=168)
for x in t.teamplayer_set.all():
if x.captain:
print "%s (Captain)" % (x.player.name)
else:
print x.player.name
Not sure how I would customize that generated related_name, but at least I know I can get to the data from the template without adding additional query results into the context.
|
Python: For each list element apply a function across the list
|
Given [1,2,3,4,5], how can I do something like
1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5
I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return (1,5).
So basically I would like to do something like
for each element i in the list
map some function across all elements in the list, taking i and j as parameters
store the result in a master list, find the minimum value in the master list, and return the arguments i, jused to calculate this minimum value.
In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.
|
You can do this using list comprehensions and min() (Python 3.0 code):
>>> nums = [1,2,3,4,5]
>>> [(x,y) for x in nums for y in nums]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
>>> min(_, key=lambda pair: pair[0]/pair[1])
(1, 5)
Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do from __future__ import division so that 1/5 correctly equals 0.2 instead of 0.
|
How to print in Python without newline or space?
|
The question is in the title.
I'd like to do in python what I do in this example in c:
#include <stdio.h>
int main() {
int i;
for (i=0; i<10; i++) printf(".");
return 0;
}
Output:
..........
In Python:
>>> for i in xrange(0,10): print '.'
.
.
.
.
.
.
.
.
.
.
>>> for i in xrange(0,10): print '.',
. . . . . . . . . .
In Python print will add a \n or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the stdout (I don't know if it's worded correctly).
|
General way
import sys
sys.stdout.write('.')
You may also need to call
sys.stdout.flush()
to ensure stdout is flushed immediately.
Python 2.6+
From Python 2.6 you can import the print function from Python 3:
from __future__ import print_function
This allows you to use the Python 3 solution below.
Python 3
In Python 3, the print statement has been changed into a function. In Python 3, you can instead do:
print('.', end="")
This also works in Python 2, provided that you've used from __future__ import print_function.
If you are having trouble with buffering, you can flush the output by adding flush=True keyword argument:
print('.', end="", flush=True)
|
Python join, why is it string.join(list) instead of list.join(string)?
|
This has always confused me. It seems like this would be nicer:
my_list = ["Hello", "world"]
print my_list.join("-")
# Produce: "Hello-world"
Than this:
my_list = ["Hello", "world"]
print "-".join(my_list)
# Produce: "Hello-world"
Is there a specific reason it does it like this?
|
It's because any iterable can be joined, not just lists, but the result and the "joiner" are always strings.
E.G:
import urllib2
print '\n############\n'.join(
urllib2.urlopen('http://data.stackexchange.com/users/7095'))
|
How to write the Fibonacci Sequence in Python
|
I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening.
startNumber = int(raw_input("Enter the start number here "))
endNumber = int(raw_input("Enter the end number here "))
def fib(n):
if n < 2:
return n
return fib(n-2) + fib(n-1)
print map(fib, range(startNumber, endNumber))
Someone pointed out in my Part II (which was closed for being a duplicate - http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome.
I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?).
What I have so far is no actual coding but rather:
Write Fib sequence formula to infinite
Display startNumber to endNumber only from Fib sequence.
I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.
|
There is lots of information about the Fibonacci Sequence on wikipedia and on wolfram. A lot more than you may need. Anyway it is a good thing to learn how to use these resources to find (quickly if possible) what you need.
Write Fib sequence formula to infinite
In math, it's given in a recursive form:
In programming, infinite doesn't exist. You can use a recursive form translating the math form directly in your language, for example in Python it becomes:
def F(n):
if n == 0: return 0
elif n == 1: return 1
else: return F(n-1)+F(n-2)
Try it in your favourite language and see that this form requires a lot of time as n gets bigger. In fact, this is O(2n) in time.
Go on on the sites I linked to you and will see this (on wolfram):
This one is pretty easy to implement and very, very fast to compute, in Python:
from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
An other way to do it is following the definition (from wikipedia):
The first number of the sequence is 0,
the second number is 1, and each
subsequent number is equal to the sum
of the previous two numbers of the
sequence itself, yielding the sequence
0, 1, 1, 2, 3, 5, 8, etc.
If your language supports iterators you may do something like:
def F():
a,b = 0,1
yield a
yield b
while True:
a, b = b, a + b
yield b
Display startNumber to endNumber only from Fib sequence.
Once you know how to generate Fibonacci Numbers you just have to cycle trough the numbers and check if they verify the given conditions.
Suppose now you wrote a f(n) that returns the n-th term of the Fibonacci Sequence (like the one with sqrt(5) )
In most languages you can do something like:
def SubFib(startNumber, endNumber):
n = 0
cur = f(n)
while cur <= endNumber:
if startNumber <= cur:
print cur
n += 1
cur = f(n)
In python I'd use the iterator form and go for:
def SubFib(startNumber, endNumber):
for cur in F():
if cur > endNumber: return
if cur >= startNumber:
yield cur
for i in SubFib(10, 200):
print i
My hint is to learn to read what you need. Project Euler (google for it) will train you to do so :P
Good luck and have fun!
|
Confusion about global variables in python
|
I'm new to python, so please excuse what is probably a pretty dumb question.
Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it.
I have two scripts:
one.py:
-------
def my_function():
if _debug:
print "debugging!"
two.py:
-------
from one import *
_debug = False
my_function()
Running two.py generates an error:
NameError: global name '_debug' is not defined
Can anyone tell me what I'm doing wrong?
|
There are more problems than just the leading underscore I'm afraid.
When you call my_function(), it still won't have your debug variable in its namespace, unless you import it from two.py.
Of course, doing that means you'll end up with cyclic dependencies (one.py -> two.py -> one.py), and you'll get NameErrors unless you refactor where various things are imported and declared.
One solution would be to create a simple third module which defines 'constants' like this, which can be safely imported from anywhere, e.g.:
constants.py
------------
debug = True
one.py
------
from constants import debug
#...
two.py
------
from constants import debug
#...
However, I would recommend just using the built in logging module for this - why not? It's easy to configure, simpler to use, reliable, flexible and extensible.
|
Is there a Python equivalent of Perl's x operator?
|
In Perl, I can replicate strings with the 'x' operator:
$str = "x" x 5;
Can I do something similar in Python?
|
>>> "blah" * 5
'blahblahblahblahblah'
|
Python's os.path choking on Hebrew filenames
|
I'm writing a script that has to move some file around, but unfortunately it doesn't seem os.path plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory:
Now consider this code that goes over the files in this directory:
files = os.listdir('test_source')
for f in files:
pf = os.path.join('test_source', f)
print pf, os.path.exists(pf)
The output is:
test_source\ex True
test_source\joe True
test_source\mie.txt True
test_source\__()'''.txt True
test_source\????.txt False
Notice how os.path.exists thinks that the hebrew-named file doesn't even exist?
How can I fix this?
ActivePython 2.5.2 on Windows XP Home SP2
|
Hmm, after some digging it appears that when supplying os.listdir a unicode string, this kinda works:
files = os.listdir(u'test_source')
for f in files:
pf = os.path.join(u'test_source', f)
print pf.encode('ascii', 'replace'), os.path.exists(pf)
===>
test_source\ex True
test_source\joe True
test_source\mie.txt True
test_source\__()'''.txt True
test_source\????.txt True
Some important observations here:
Windows XP (like all NT derivatives) stores all filenames in unicode
os.listdir (and similar functions, like os.walk) should be passed a unicode string in order to work correctly with unicode paths. Here's a quote from the aforementioned link:
os.listdir(), which returns filenames,
raises an issue: should it return the
Unicode version of filenames, or
should it return 8-bit strings
containing the encoded versions?
os.listdir() will do both, depending
on whether you provided the directory
path as an 8-bit string or a Unicode
string. If you pass a Unicode string
as the path, filenames will be decoded
using the filesystem's encoding and a
list of Unicode strings will be
returned, while passing an 8-bit path
will return the 8-bit versions of the
filenames.
And lastly, print wants an ascii string, not unicode, so the path has to be encoded to ascii.
|
Deleting multiple elements from a list
|
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].
I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.
|
If you're deleting multiple non-adjacent items, then what you describe is the best way (and yes, be sure to start from the highest index).
If your items are adjacent, you can use the slice assignment syntax:
a[2:10] = []
|
Django workflow when modifying models frequently?
|
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome..
Modify the model.
Delete the test database. (always a simple sqlite database for me.)
Run "syncdb".
Generate some test data via code.
goto 1.
A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\
TIA.
|
Steps 2 & 3 can be done in one step:
manage.py reset appname
Step 4 is most easily managed, from my understanding, by using fixtures
|
Python string.join(list) on object array rather than string array
|
In Python, I can do:
>>> list = ['a', 'b', 'c']
>>> ', '.join(list)
'a, b, c'
Is there any easy way to do the same when I have a list of objects?
>>> class Obj:
... def __str__(self):
... return 'name'
...
>>> list = [Obj(), Obj(), Obj()]
>>> ', '.join(list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, instance found
Or do I have to resort to a for loop?
|
You could use a list comprehension or a generator expression instead:
', '.join([str(x) for x in list]) # list comprehension
', '.join(str(x) for x in list) # generator expression
|
Python element-wise tuple operations like sum
|
Is there anyway to get tuple operations in Python to work like this:
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
instead of:
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
I know it works like that because the __add__ and __mul__ methods are defined to work like that. So the only way would be to redefine them?
|
import operator
tuple(map(operator.add, a, b))
|
How to make python gracefully fail?
|
I was just wondering how do you make python fail in a user defined way in all possible errors.
For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item.
If anyone can help me with this it would be greatly appreciated!
Thanks a lot!
Jason
|
The following are a few basic strategies I regularly use in my more-than-trivial scripts and medium-size applications.
Tip 1: Trap the error at every level where it makes sense to continue processing. In your case it may be in the inside the loop. You don't have to protect every single line or every single function call, but only the places where it makes a difference to survive the error.
Tip 2: Use the logging module to report what happened in a way that is configurable independently from how you compose the module with other modules in a larger applications. Start importing the root logger in your module, then, using it in a few different places, you may eventually figure out a more sensible logging hierarchy.
import logging
logger = logging.getLogger()
for item in items:
try:
process(item)
except Exception, exc:
logger.warn("error while processing item: %s", exc)
Tip 3: define an "application exception", eventually you may want to define a hierarchy of such exception but this is better discovered when the need arise. Use such exception(s) to "bubble out" when the data you are dealing with are not what you expected or to signal inconsistent situations, while separating them from the normal standard exception arising from regular bugs or problems outside the modeled domain (IO errors etc).
class DomainException(Exception):
"""Life is not what I expected"""
def process(item):
# There is no way that this item can be processed, so bail out quickly.
# Here you are assuming that your caller will report this error but probably
# it will be able to process the other items.
if item.foo > item.bar:
raise DomainException("bad news")
# Everybody knows that every item has more that 10 wickets, so
# the following instruction is assumed always being successful.
# But even if luck is not on our side, our caller will be able to
# cope with this situation and keep on working
item.wickets[10] *= 2
The main function is the outmost checkpoint: finally deal here with the possible ways your task finished. If this was not a shell script (but e.g. the processing beneath a dialog in an UI application or an operation after a POST in a web application) only the way you report the error changes (and the use of the logging method completely separates the implementation of the processing from its interface).
def main():
try:
do_all_the_processing()
return 0
except DomainException, exc:
logger.error("I couldn't finish. The reason is: %s", exc)
return 1
except Exception, exc:
logger.error("Unexpected error: %s - %s", exc.__class__.__name__, exc)
# In this case you may want to forward a stacktrace to the developers via e-mail
return 1
except BaseException:
logger.info("user stop") # this deals with a ctrl-c
return 1
if __name__ == '__main__':
sys.exit(main())
|
How do I compile a Visual Studio project from the command-line?
|
I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using Monotone, CMake, Visual Studio Express 2008, and custom tests.
All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI.
The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.
|
I know of two ways to do it.
Method 1
The first method (which I prefer) is to use msbuild:
msbuild project.sln /Flags...
Method 2
You can also run:
vcexpress project.sln /build /Flags...
The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.
Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).
So, the end result might be:
os.system("msbuild project.sln /p:Configuration=Debug")
You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).
|
Valid use case for django admin?
|
I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django people define "trust", especially the bolded bit...
From The Django Book, Chapter 18:
The admin is designed to be used by
people who you, the developer, trust.
This doesnât just mean âpeople who
have been authenticated;â it means
that Django assumes that your content
editors can be trusted to do the right
thing.
This means that thereâs no âapprovalâ
process for editing content â if you
trust your users, nobody needs to
approve of their edits. It also means
that the permission system, while
powerful, has no support for limiting
access on a per-object basis. If you
trust someone to edit their own
stories, you trust them not to edit
anyone elseâs without permission.
Is this one of those use cases that fits with django's admin module, or is it just a specialized view for a non-trusted user?
|
No, the Django admin is not suited for individual user profiles, each user would be able to see, and edit, all other user profiles. This is suited more to an administrator who has to manage all the users at once.
What you need to build is a user profile page. Django already has a nice login system courtesy of the django.contrib.auth module. You can easily integrate this into your pages, and its exactly what the Django admin uses to authenticate users.
Next you'll have to build a simple page that exposes that specific user's profile information based on their User model. This should be relatively painless as it will only require one view and one template, and the template can take advantage of ModelForms.
|
Is Django a good choice for a security critical application?
|
Is Django a good choice for a security critical application?
I am asking this because most of the online banking software is built using Java. Is there any real reason for this?
|
Actually, the security in Java and Python is the same. Digest-only password handling, cookies that timeout rapidly, careful deletion of sessions, multi-factor authentication. None of this is unique to a Java framework or a Python framework like Django.
Django, indeed, has a security backend architecture that allows you to add your own LDAP (or AD) connection, possibly changing the digest technique used.
Django has a Profile model where you can keep additional authentication factors.
Django offers a few standard decorators for view function authorization checking. Since Python is so flexible, you can trivially write your own decorator functions to layer in different or additional authentication checking.
Security is a number of first-class features in Django.
|
Regular expression to extract URL from an HTML link
|
Iâm a newbie in Python. Iâm learning regexes, but I need help here.
Here comes the HTML source:
<a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
Iâm trying to code a tool that only prints out http://ptop.se. Can you help me please?
|
If you're only looking for one:
import re
match = re.search(r'href=[\'"]?([^\'" >]+)', s)
if match:
print match.group(0)
If you have a long string, and want every instance of the pattern in it:
import re
urls = re.findall(r'href=[\'"]?([^\'" >]+)', s)
print ', '.join(urls)
Where s is the string that you're looking for matches in.
Quick explanation of the regexp bits:
r'...' is a "raw" string. It stops you having to worry about escaping characters quite as much as you normally would. (\ especially -- in a raw string a \ is just a \. In a regular string you'd have to do \\ every time, and that gets old in regexps.)
"href=[\'"]?" says to match "href=", possibly followed by a ' or ". "Possibly" because it's hard to say how horrible the HTML you're looking at is, and the quotes aren't strictly required.
Enclosing the next bit in "()" says to make it a "group", which means to split it out and return it separately to us. It's just a way to say "this is the part of the pattern I'm interested in."
"[^\'" >]+" says to match any characters that aren't ', ", >, or a space. Essentially this is a list of characters that are an end to the URL. It lets us avoid trying to write a regexp that reliably matches a full URL, which can be a bit complicated.
The suggestion in another answer to use BeautifulSoup isn't bad, but it does introduce a higher level of external requirements. Plus it doesn't help you in your stated goal of learning regexps, which I'd assume this specific html-parsing project is just a part of.
It's pretty easy to do:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_to_parse)
for tag in soup.findAll('a', href=True):
print tag['href']
Once you've installed BeautifulSoup, anyway.
|
What's the best serialization method for objects in memcached?
|
My Python application currently uses the python-memcached API to set and get objects in memcached. This API uses Python's native pickle module to serialize and de-serialize Python objects. This API makes it simple and fast to store nested Python lists, dictionaries and tuples in memcached, and reading these objects back into the application is completely transparent -- it just works.But I don't want to be limited to using Python exclusively, and if all the memcached objects are serialized with pickle, then clients written in other languages won't work.Here are the cross-platform serialization options I've considered:
XML - the main benefit is that it's human-readable, but that's not important in this application. XML also takes a lot space, and it's expensive to parse.
JSON - seems like a good cross-platform standard, but I'm not sure it retains the character of object types when read back from memcached. For example, according to this post tuples are transformed into lists when using simplejson; also, it seems like adding elements to the JSON structure could break code written to the old structure
Google Protocol Buffers - I'm really interested in this because it seems very fast and compact -- at least 10 times smaller and faster than XML; it's not human-readable, but that's not important for this app; and it seems designed to support growing the structure without breaking old code
Considering the priorities for this app, what's the ideal object serialization method for memcached?
Cross-platform support (Python, Java, C#, C++, Ruby, Perl)
Handling nested data structures
Fast serialization/de-serialization
Minimum memory footprint
Flexibility to change structure without breaking old code
|
I tried several methods and settled on compressed JSON as the best balance between speed and memory footprint. Python's native Pickle function is slightly faster, but the resulting objects can't be used with non-Python clients.
I'm seeing 3:1 compression so all the data fits in memcache and the app gets sub-10ms response times including page rendering.
Here's a comparison of JSON, Thrift, Protocol Buffers and YAML, with and without compression:
http://bouncybouncy.net/ramblings/posts/more_on_json_vs_thrift_and_protocol_buffers/
Looks like this test got the same results I did with compressed JSON. Since I don't need to pre-define each structure, this seems like the fastest and smallest cross-platform answer.
|
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?
|
I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post.
Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want.
Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something?
It would be perfect if I could just get the entire difference in seconds.
|
It seems that Python 2.7 has introduced a total_seconds() method, which is what you were looking for, I believe!
|
Identifying numeric and array types in numpy
|
Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard arithmetic operators, +, -, *, /, **).
Some examples of the behavior I'm looking for
>>> is_numeric(5)
True
>>> is_numeric(123.345)
True
>>> is_numeric('123.345')
False
>>> is_numeric(decimal.Decimal('123.345'))
True
>>> is_numeric(True)
False
>>> is_numeric([1, 2, 3])
False
>>> is_numeric([1, '2', 3])
False
>>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9])
>>> is_numeric(a)
True
>>> is_numeric(a[0])
True
>>> is_numeric(a[1])
True
>>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])])
True
>>> is_numeric(numpy.array(['1'])
False
If no such function exists, I know it shouldn't be hard to write one, something like
isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray))
but are there other numeric types I should include in the list?
|
As others have answered, there could be other numeric types besides the ones you mention.
One approach would be to check explicitly for the capabilities you want, with something like
# Python 2
def is_numeric(obj):
attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__']
return all(hasattr(obj, attr) for attr in attrs)
# Python 3
def is_numeric(obj):
attrs = ['__add__', '__sub__', '__mul__', '__truediv__', '__pow__']
return all(hasattr(obj, attr) for attr in attrs)
This works for all your examples except the last one, numpy.array(['1']). That's because numpy.ndarray has the special methods for numeric operations but raises TypeError if you try to use them inappropriately with string or object arrays. You could add an explicit check for this like
... and not (isinstance(obj, ndarray) and obj.dtype.kind in 'OSU')
This may be good enough.
But... you can never be 100% sure that somebody won't define another type with the same behavior, so a more foolproof way is to actually try to do a calculation and catch the exception, something like
def is_numeric_paranoid(obj):
try:
obj+obj, obj-obj, obj*obj, obj**obj, obj/obj
except ZeroDivisionError:
return True
except Exception:
return False
else:
return True
but depending on how often you plan to call use it and with what arguments, this may not be practical (it can be potentially slow, e.g. with large arrays).
|
Case insensitive Python regular expression without re.compile
|
In Python, I can compile a regular expression to be case-insensitive using re.compile:
>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>>
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>
Is there a way to do the same, but without using re.compile. I can't find anything like Perl's i suffix (e.g. m/test/i) in the documentation.
|
Pass re.IGNORECASE to the flags param of search, match, or sub:
re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)
|
Using web.py as non blocking http-server
|
while learning some basic programming with python, i found web.py. i
got stuck with a stupid problem:
i wrote a simple console app with a main loop that proccesses items
from a queue in seperate threads. my goal is to use web.py to add
items to my queue and report status of the queue via web request. i
got this running as a module but can´t integrate it into my main app.
my problem is when i start the http server with app.run() it blocks my
main loop.
also tried to start it with thread.start_new_thread but it still
blocks.
is there an easy way to run web.py´s integrated http server in the
background within my app.
in the likely event that i am a victim of a fundamental
missunderstanding, any attempt to clarify my error in reasoning would
help ;.) ( please bear with me, i am a beginner :-)
|
I found a working solution. In a seperate module i create my webserver:
import web
import threading
class MyWebserver(threading.Thread):
def run (self):
urls = ('/', 'MyWebserver')
app = web.application(urls, globals())
app.run()
def POST ...
In the main programm i just call
MyWebserver().start()
and than go on with whatever i want while having the webserver working in the background.
|
How can you use Python in Vim?
|
I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:
%!python for i in xrange(25); print 6*i \n
How can you do such tweaks direcly in Vim? [Solved]
[Clarification] I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.
[?] Can someone elaborate this point:
"your script can read from stdin to operate directly on the lines given (., %, ...)."
[Further Clarification]
If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:
:4-7!python -c "print 'hello'"
The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:
:7,32,99!python -c "print 'hello'"
Clearly not working. How?
|
In any of your vim windows, type something like this:
for x in range(1,10):
print '-> %d' % x
Visually select both of those lines (V to start visual mode), and type the following:
:!python
Because you pressed ':' in visual mode, that will end up looking like:
:'<,'>!python
Hit enter and the selection is replaced by the output of the print statements. You could easily turn it into a mapping:
:vnoremap <f5> :!python<CR>
|
Both Python 2 and 3 in Emacs
|
I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well.
Here is how the different versions are set up in /usr/bin:
python -> python2.6*
python2 -> python2.6*
python2.6*
python3 -> python3.0*
python3.0*
Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.
|
If you are using python-mode.el you can try to change py-which-shell. In order to do this on a per-file basis you can put
# -*- py-which-shell: "python3"; -*-
at the first line of your file - or at the second line if the first line starts with #!.
Another choice is to put
# Local Variables:
# py-which-shell: "python3"
# End:
at the end of your file. Perhaps you should give the full path to python3 instead of just "python3".
|
Converting date between DD/MM/YYYY and YYYY-MM-DD?
|
Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.
This almost works, but fails because I don't provide time:
from datetime import datetime
lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d")
#ValueError: time data did not match format: data=21/12/2008 fmt=%Y-%m-%d
print lastconnection
I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.
|
Your example code is wrong. This works:
import datetime
datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.
|
Django: How to create a model dynamically just for testing
|
I have a Django app that requires a settings attribute in the form of:
RELATED_MODELS = ('appname1.modelname1.attribute1',
'appname1.modelname2.attribute2',
'appname2.modelname3.attribute3', ...)
Then hooks their post_save signal to update some other fixed model depending on the attributeN defined.
I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)
Solutions that allow me to use test fixtures would be great.
|
You can put your tests in a tests/ subdirectory of the app (rather than a tests.py file), and include a tests/models.py with the test-only models.
Then provide a test-running script (example) that includes your tests/ "app" in INSTALLED_APPS. (This doesn't work when running app tests from a real project, which won't have the tests app in INSTALLED_APPS, but I rarely find it useful to run reusable app tests from a project, and Django 1.6+ doesn't by default.)
(NOTE: The alternative dynamic method described below only works in Django 1.1+ if your test case subclasses TransactionTestCase - which slows down your tests significantly - and no longer works at all in Django 1.7+. It's left here only for historical interest; don't use it.)
At the beginning of your tests (i.e. in a setUp method, or at the beginning of a set of doctests), you can dynamically add "myapp.tests" to the INSTALLED_APPS setting, and then do this:
from django.core.management import call_command
from django.db.models import loading
loading.cache.loaded = False
call_command('syncdb', verbosity=0)
Then at the end of your tests, you should clean up by restoring the old version of INSTALLED_APPS and clearing the app cache again.
This class encapsulates the pattern so it doesn't clutter up your test code quite as much.
|
Py2exe for Python 3.0
|
I am looking for a Python3.0 version of "py2exe". I tried running 2to3 on the source for py2exe but the code remained broken.
Any ideas?
|
Update 2014-05-15
py2exe for Python 3.x is now released! Get it on PyPI.
Old information
Have a look at the py2exe SourceForge project SVN repository at:
http://py2exe.svn.sourceforge.net/
The last I looked at it, it said the last update was August 2009. But keep an eye on that to see if there's any Python 3 work in-progress.
I've also submitted two feature requests on the py2exe tracker. So far, no feedback on them:
Support Python 3.x
Project roadmap
|
How do i install pyCurl?
|
I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.
i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.
|
TL,DR
Get a binary from this website: http://www.lfd.uci.edu/~gohlke/pythonlibs/
Direct links: 2.6 32bit,
2.7 32bit,2.6 64bit, 2.7 64bit
For pycURL, both pip and easy_install will fail on Windows.
I also tried to download and install the pycURL package manually, after
downloading cURL, but that didn't work either, even if specifying the
CURL_DIR ( it complained that it cannot find 'lib\libcurl.lib' ). From what
I can gather from the README, what it needs in the CURL_DIR is the source
distribution of cURL, not the executable.
Downloading the precompiled version from the official pycURL
repository will probably get you
nowhere, because it requires Python 2.5. It will not work with 2.6.
The only easy way at the moment seems to be
this
unofficial release. It an executable installer, and I have used it without any
issues with Python 2.6. A version for Python
2.7
is available from the same site.
You might also want to consider using requests, a popular alternative to pycURL. It's a pleasure to use, and is actively developed.
|
Is there a good dependency analysis tool for Python?
|
Dependency analysis programs help us organize code by controlling the dependencies between modules in our code. When one module is a circular dependency of another module, it is a clue to find a way to turn that into a unidirectional dependency or merge two modules into one module.
What is the best dependency analysis tool for Python code?
|
I recommend using snakefood for creating graphical dependency graphs of Python projects. It detects dependencies nicely enough to immediately see areas for refactorisation. Its usage is pretty straightforward if you read a little bit of documentation.
Of course, you can omit the graph-creation step and receive a dependency dictionary in a file instead.
|
How to overwrite some bytes in the middle of a file with Python?
|
I'd like to be able to overwrite some bytes at a given offset in a file using Python.
My attempts have failed miserably and resulted in:
overwriting the bytes at the offset but also truncating the file just after (file mode = "w" or "w+")
appending the bytes at the end of the file (file mode = "a" or "a+")
Is it possible to achieve this with Python in a portable way?
|
Try this:
fh = open("filename.ext", "r+b")
fh.seek(offset)
fh.write(bytes)
fh.close()
|
Explain Python's slice notation
|
I need a good explanation (references are a plus) on Python's slice notation.
To me, this notation needs a bit of picking up.
It looks extremely powerful, but I haven't quite got my head around it.
|
It's pretty simple really:
a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
There is also the step value, which can be used with any of the above:
a[start:end:step] # start through not past end, by step
The key point to remember is that the :end value represents the first value that is not in the selected slice. So, the difference beween end and start is the number of elements selected (if step is 1, the default).
The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning. So:
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.
|
How can I make a time delay in Python?
|
I would like to know how to put a time delay in a Python script.
|
import time
time.sleep(5) # delays for 5 seconds
Here is another example where something is run once a minute:
import time
while True:
print "This prints once a minute."
time.sleep(60) # Delay for 1 minute (60 seconds)
|
Python read a single character from the user
|
Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like getch()). I know there's a function in Windows for it, but I'd like something that is cross-platform.
|
Here's a link to a site that says how you can read a single character in Windows, Linux and OSX: http://code.activestate.com/recipes/134892/
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
|
Is there a way to get the current ref count of an object in Python?
|
Is there a way to get the current ref count of an object in Python?
|
According to some Python 2.0 reference (http://www.brunningonline.net/simon/python/quick-ref2_0.html), the sys module contains a function:
import sys
sys.getrefcount(object) #-- Returns the reference count of the object.
Generally 1 higher than you might expect, because of object arg temp reference.
|
How to write a functional test for a DBUS service written in Python?
|
(Title was: "How to write a unit test for a DBUS service written in Python?")
I've started to write a DBUS service using dbus-python, but I'm having trouble writing a test case for it.
Here is an example of the test I am trying to create. Notice that I have put a GLib event loop in the setUp(), this is where the problem hits:
import unittest
import gobject
import dbus
import dbus.service
import dbus.glib
class MyDBUSService(dbus.service.Object):
def __init__(self):
bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus())
dbus.service.Object.__init__(self, bus_name, '/test/helloservice')
@dbus.service.method('test.helloservice')
def hello(self):
return "Hello World!"
class BaseTestCase(unittest.TestCase):
def setUp(self):
myservice = MyDBUSService()
loop = gobject.MainLoop()
loop.run()
# === Test blocks here ===
def testHelloService(self):
bus = dbus.SessionBus()
helloservice = bus.get_object('test.helloservice', '/test/helloservice')
hello = helloservice.get_dbus_method('hello', 'test.helloservice')
assert hello() == "Hello World!"
if __name__ == '__main__':
unittest.main()
My problem is that the DBUS implementation requires you to start an event loop so that it can start dispatching events. The common approach is to use GLib's gobject.MainLoop().start() (although I'm not married to this approach, if someone has a better suggestion). If you don't start an event loop, the service still blocks, and you also cannot query it.
If I start my service in the test, the event loop blocks the test from completing. I know the service is working because I can query the service externally using the qdbus tool, but I can't automate this inside the test that starts it.
I'm considering doing some kind of process forking inside the test to handle this, but I was hoping someone might have a neater solution, or at least a good starting place for how I would write a test like this.
|
With some help from Ali A's post, I have managed to solve my problem. The blocking event loop needed to be launched into a separate process, so that it can listen for events without blocking the test.
Please be aware my question title contained some incorrect terminology, I was trying to write a functional test, as opposed to a unit test. I was aware of the distinction, but didn't realise my mistake until later.
I've adjusted the example in my question. It loosely resembles the "test_pidavim.py" example, but uses an import for "dbus.glib" to handle the glib loop dependencies instead of coding in all the DBusGMainLoop stuff:
import unittest
import os
import sys
import subprocess
import time
import dbus
import dbus.service
import dbus.glib
import gobject
class MyDBUSService(dbus.service.Object):
def __init__(self):
bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus())
dbus.service.Object.__init__(self, bus_name, '/test/helloservice')
def listen(self):
loop = gobject.MainLoop()
loop.run()
@dbus.service.method('test.helloservice')
def hello(self):
return "Hello World!"
class BaseTestCase(unittest.TestCase):
def setUp(self):
env = os.environ.copy()
self.p = subprocess.Popen(['python', './dbus_practice.py', 'server'], env=env)
# Wait for the service to become available
time.sleep(1)
assert self.p.stdout == None
assert self.p.stderr == None
def testHelloService(self):
bus = dbus.SessionBus()
helloservice = bus.get_object('test.helloservice', '/test/helloservice')
hello = helloservice.get_dbus_method('hello', 'test.helloservice')
assert hello() == "Hello World!"
def tearDown(self):
# terminate() not supported in Python 2.5
#self.p.terminate()
os.kill(self.p.pid, 15)
if __name__ == '__main__':
arg = ""
if len(sys.argv) > 1:
arg = sys.argv[1]
if arg == "server":
myservice = MyDBUSService()
myservice.listen()
else:
unittest.main()
|
Getting the class name of an instance in Python
|
How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?
Was thinking maybe the inspect module might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the __class__ member, I'm not sure how to get at this information.
|
Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.
>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
This method works with new-style classes only. Your code might use some old-style classes. The following works for both:
x.__class__.__name__
|
How to print a string without including '\n' in Python
|
Suppose my string is:
' Hai Hello\nGood eve\n'
How do I eliminate the '\n' in between and make a string print like :
Hai Hello Good eve
?
|
If you don't want the newline at the end of the print statement:
import sys
sys.stdout.write("text")
|
Django Installed Apps Location
|
I am an experienced PHP programmer using Django for the first time, and I think it is incredible!
I have a project that has a lot of apps, so I wanted to group them in an apps folder.
So the structure of the project is:
/project/
/project/apps/
/project/apps/app1/
/project/apps/app2
Then in Django settings I have put this:
INSTALLED_APPS = (
'project.apps.app1',
'project.apps.app2',
)
This does not seem to work?
Any ideas on how you can put all your apps into a seprate folder and not in the project root?
Many thanks.
|
Make sure that the '__init__.py' file is in your apps directory, if it's not there it won't be recognized as part of the package.
So each of the folders here should have '__init__.py' file in it. (empty is fine).
/project/
/project/apps/
/project/apps/app1/
/project/apps/app2
Then as long as your root 'module' folder is in your PYTHONPATH you'll be able to import from your apps.
Here's the documentation regarding the python search path for your reading pleasure:
http://docs.python.org/install/index.html#modifying-python-s-search-path
And a nice simple explanation of what __init__.py file is for:
http://effbot.org/pyfaq/what-is-init-py-used-for.htm
|
How to copy a directory and its contents to an existing location using Python?
|
I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the shutil.copytree() function expects that the destination path not exist beforehand.
The exact result I'm looking for is to copy an entire folder structure on top of another, overwriting silently on any duplicates found. Before I jump in and start writing my own function to do this I thought I'd ask if anyone knows of an existing recipe or snippet that does this.
|
distutils.dir_util.copy_tree does what you want.
Copy an entire directory tree src to a
new location dst. Both src and dst
must be directory names. If src is not
a directory, raise DistutilsFileError.
If dst does not exist, it is created
with mkpath(). The end result of the
copy is that every file in src is
copied to dst, and directories under
src are recursively copied to dst.
Return the list of files that were
copied or might have been copied,
using their output name. The return
value is unaffected by update or
dry_run: it is simply the list of all
files under src, with the names
changed to be under dst.
(more documentation at the above url)
|
Delete file from zipfile with the ZipFile Module
|
The only way i came up for deleting a file from a zipfile was to create a temporary zipfile without the file to be deleted and then rename it to the original filename.
In python 2.4 the ZipInfo class had an attribute file_offset, so it was possible to create a second zip file and copy the data to other file without decompress/recompressing.
This file_offset is missing in python 2.6, so is there another option than creating another zipfile by uncompressing every file and then recompressing it again?
Is there maybe a direct way of deleting a file in the zipfile, i searched and didn't find anything.
Thanks in advance.
|
The following snippet worked for me (deletes all *.exe files from a Zip archive):
zin = zipfile.ZipFile ('archive.zip', 'r')
zout = zipfile.ZipFile ('archve_new.zip', 'w')
for item in zin.infolist():
buffer = zin.read(item.filename)
if (item.filename[-4:] != '.exe'):
zout.writestr(item, buffer)
zout.close()
zin.close()
If you read everything into memory, you can eliminate the need for a second file. However, this snippet recompresses everything.
After closer inspection the ZipInfo.header_offset is the offset from the file start. The name is misleading, but the main Zip header is actually stored at the end of the file. My hex editor confirms this.
So the problem you'll run into is the following: You need to delete the directory entry in the main header as well or it will point to a file that doesn't exist anymore. Leaving the main header intact might work if you keep the local header of the file you're deleting as well, but I'm not sure about that. How did you do it with the old module?
Without modifying the main header I get an error "missing X bytes in zipfile" when I open it. This might help you to find out how to modify the main header.
|
Python: List vs Dict for look up table
|
I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a list or dict?
I know you can do something like this for both:
if something in dict_of_stuff:
pass
and
if something in list_of_stuff:
pass
My thought is the dict will be faster and more efficient.
Thanks for your help.
EDIT 1
Little more info on what I'm trying to do. Euler Problem 92. I'm making a look up table to see if a value calculated has all ready been calculated.
EDIT 2
Efficiency for look up.
EDIT 3
There are no values assosiated with the value...so would a set be better?
|
Speed
Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.
Memory
Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchling in Beautiful Code, the implementation tries to keep the hash 2/3 full, so you might waste quite some memory.
If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering.
|
Elegant ways to return multiple values from a function
|
It seems like in most mainstream programming languages, returning multiple values from a function is an extremely awkward thing.
The typical solutions are to make either a struct or a plain old data class and return that, or to pass at least some of the parameters by reference or pointer instead of returning them.
Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass.
The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity.
Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types.
The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:
a, b = foo(c) # a and b are regular variables.
myTuple = foo(c) # myTuple is a tuple of (a, b)
Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.
|
Pretty much all ML-influenced functional langues (which is most of them) also have great tuple support that makes this sort of thing trivial.
For C++ I like boost::tuple plus boost::tie (or std::tr1 if you have it)
typedef boost::tuple<double,double,double> XYZ;
XYZ foo();
double x,y,z;
boost::tie(x,y,z) = foo();
or a less contrived example
MyMultimap::iterator lower,upper;
boost::tie(lower,upper) = some_map.equal_range(key);
|
Extension methods in Python
|
Does Python have extension methods like C#? Is it possible to call a method like:
MyRandomMethod()
on existing types like int?
myInt.MyRandomMethod()
|
You can add whatever methods you like on class objects defined in Python code (AKA monkey patching):
>>> class A(object):
>>> pass
>>> def stuff(self):
>>> print self
>>> A.test = stuff
>>> A().test()
This does not work on builtin types, because their __dict__ is not writable (it's a dictproxy).
So no, there is no "real" extension method mechanism in Python.
|
What's the bad magic number error?
|
What's the "Bad magic number" ImportError in python, and how do I fix it?
The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.
The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:
Traceback (most recent call last):
File "run.py", line 7, in <module>
from Normalization import Normalizer
|
The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type.
Python puts a similar marker into its pyc files when it creates them.
Then the python interpreter makes sure this number is correct when loading it.
Anything that damages this magic number will cause your problem. This includes editing the pyc file or trying to run a pyc from a different version of python (usually later) than your interpreter.
If they are your pyc files, just delete them and let the interpreter re-compile the py files. On UNIX type systems, that could be something as simple as:
rm *.pyc
or:
find . -name '*.pyc' -delete
If they are not yours, you'll have to either get the py files for re-compilation, or an interpreter that can run the pyc files with that particular magic value.
One thing that might be causing the intermittent nature. The pyc that's causing the problem may only be imported under certain conditions. It's highly unlikely it would import sometimes. You should check the actual full stack trace when the import fails?
As an aside, the first word of all my 2.5.1(r251:54863) pyc files is 62131, 2.6.1(r261:67517) is 62161. The list of all magic numbers can be found in Python/import.c, reproduced here for completeness (current as at the time the answer was posted, it may have changed since then):
1.5: 20121
1.5.1: 20121
1.5.2: 20121
1.6: 50428
2.0: 50823
2.0.1: 50823
2.1: 60202
2.1.1: 60202
2.1.2: 60202
2.2: 60717
2.3a0: 62011
2.3a0: 62021
2.3a0: 62011
2.4a0: 62041
2.4a3: 62051
2.4b1: 62061
2.5a0: 62071
2.5a0: 62081
2.5a0: 62091
2.5a0: 62092
2.5b3: 62101
2.5b3: 62111
2.5c1: 62121
2.5c2: 62131
2.6a0: 62151
2.6a1: 62161
2.7a0: 62171
|
return eats exception
|
I found the following behavior at least weird:
def errors():
try:
ErrorErrorError
finally:
return 10
print errors()
# prints: 10
# It should raise: NameError: name 'ErrorErrorError' is not defined
The exception disappears when you use return inside a finally clause. Is that a bug? Is that documented anywhere?
But the real question (and the answer I will mark as correct) is:
What is the python developers' reason to allow that odd behavior?
|
The exception disappears when you use return inside a finally clause. .. Is that documented anywhere?
It is:
If finally is present, it specifies a âcleanupâ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is lost.
|
How do I write output in same place on the console?
|
I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:
output:
Downloading File FooFile.txt [47%]
I'm trying to avoid something like this:
Downloading File FooFile.txt [47%]
Downloading File FooFile.txt [48%]
Downloading File FooFile.txt [49%]
How should I go about doing this?
Duplicate: http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360
|
You can also use the carriage return:
sys.stdout.write("Download progress: %d%% \r" % (progress) )
sys.stdout.flush()
|
String formatting in Python
|
I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:
[1, 2, 3]
How do I do this in Python?
|
The previous answers have used % formatting, which is being phased out in Python 3.0+. Assuming you're using Python 2.6+, a more future-proof formatting system is described here:
http://docs.python.org/library/string.html#formatstrings
Although there are more advanced features as well, the simplest form ends up looking very close to what you wrote:
>>> "[{0}, {1}, {2}]".format(1, 2, 3)
[1, 2, 3]
|
What is the best way to remove accents in a Python unicode string?
|
I have a Unicode string in Python, and I would like to remove all the accents (diacritics).
I found on the Web an elegant way to do this in Java:
convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)
remove all the characters whose Unicode type is "diacritic".
Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3?
Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.
|
How about this:
import unicodedata
def strip_accents(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
This works on greek letters, too:
>>> strip_accents(u"A \u00c0 \u0394 \u038E")
u'A A \u0394 \u03a5'
>>>
The character category "Mn" stands for Nonspacing_Mark, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit).
And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration".
|
How to clear python interpreter console?
|
Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.
I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do.
Note: I'm running on Windows, so Ctrl+L doesn't work.
|
As you mentioned, you can do a system call:
>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()
I am not sure of any other way in Windows.
|
Getting the length of an array in Python
|
In Python, is the following the only way to get the number of elements?
arr.__len__()
If so, why the strange syntax?
|
my_list = [1,2,3,4,5]
len(my_list)
The same works for tuples:
my_tuple = (1,2,3,4,5)
len(my_tuple)
And strings, which are really just arrays of characters:
my_string = 'hello world'
len(my_string)
It was intentionally done this way so that lists, tuples and other container types didn't all need to explicitly implement a public .length() method, instead you can just check the len() of anything that implements the 'magic' __len__() method.
Sure, this may seem redundant, but length checking implementations can vary considerably, even within the same language. It's not uncommon to see one collection type use a .length() method while another type uses a .length property, while yet another uses .count(). Having a language-level keyword unifies the entry point for all these types. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.
|
Lazy Method for Reading Big File in Python?
|
I have a very big file 4GB and when I try to read it my computer hangs.
So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.
Is there any method to yield these pieces ?
I would love to have a lazy method.
|
To write a lazy function, just use yield:
def read_in_chunks(file_object, chunk_size=1024):
"""Lazy function (generator) to read a file piece by piece.
Default chunk size: 1k."""
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data
f = open('really_big_file.dat')
for piece in read_in_chunks(f):
process_data(piece)
Another option would be to use iter and a helper function:
f = open('really_big_file.dat')
def read1k():
return f.read(1024)
for piece in iter(read1k, ''):
process_data(piece)
If the file is line-based, the file object is already a lazy generator of lines:
for line in open('really_big_file.dat'):
process_data(line)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.