instruction
stringlengths 12
148
| input
stringlengths 16
30.2k
| output
stringlengths 11
27.3k
|
|---|---|---|
Best way to format integer as string with leading zeros?
|
I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt).
What the best way to translate this simple function from PHP to Python:
function add_nulls($int, $cnt=2) {
$int = intval($int);
for($i=0; $i<($cnt-strlen($int)); $i++)
$nulls .= '0';
return $nulls.$int;
}
Is there a function that can do this?
|
You can use the zfill() method to pad a string with zeros:
In [3]: str(1).zfill(2)
Out[3]: '01'
|
What is the difference between a site and an app in Django?
|
I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example.
Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mysite with one app called StackOverflow?
|
Django actually has 3 concepts here:
Project (I think this is what you're calling site): This is the directory that contains all the apps. They share a common runtime invocation and can refer to each other.
App: This is a set of views, models, and templates. Apps are often designed so they can be plugged into another project.
Site: You can designate different behaviour for an app based on the site (ie: URL) being visited. This way, the same "App" can customize itself based on whether or not the user has visited 'StackOverflow.com' or 'RackOverflow.com' (or whatever the IT-targeted version will be called), even though it's the same codebase that's handling the request.
How you arrange these is really up to your project. In a complicated case, you might do:
Project: StackOverflowProject
App: Web Version
Site: StackOverflow.com
Site: RackOverflow.com
App: XML API Version
Site: StackOverflow.com
Site: RackOverflow.com
Common non-app settings, libraries, auth, etc
Or, for a simpler project that wants to leverage an open-source plugin:
Project: StackOverflowProject
App: Stackoverflow
(No specific use of the sites feature... it's just one site)
App: Plug-in TinyMCE editor with image upload
(No specific use of the sites feature)
Aside from the fact that there needs to be a Project, and at least one app, the arrangement is very flexible; you can adapt however suits best to help abstract and manage the complexity (or simplicity) of your deployment.
|
Python mechanize - two buttons of type 'submit'
|
I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the forum and do br.submit(), it clicks on the 'attach' button instead of 'create'. Extensive Googling has yielded nothing useful for selecting a specific button in a form. Does anyone know of any methods for skipping over the first 'submit' button and clicking the second?
|
I tried using the nr parameter, without any luck.
I was able to get it to work with a combination of the name and label parameters, where "label" seems to correspond to the "value" in the HTML:
Here are my two submit buttons:
<input type="submit" name="Preview" value="Preview" />
<input type="submit" name="Create" value="Create New Page" />
... and here's the code that clicks the first one, goes back, and then clicks the second:
from mechanize import Browser
self.br = Browser()
self.br.open('http://foo.com/path/to/page.html')
self.br.select_form(name='my_form')
self.br['somefieldname'] = 'Foo'
submit_response = self.br.submit(name='Preview', label='Preview')
self.br.back()
self.br.select_form(name='my_form')
self.br['somefieldname'] = 'Bar'
submit_response = self.br.submit(name='Create', label='Create New Page')
There's a variant that also worked for me, where the "name" of the submit button is the same, such as:
<input type="submit" name="action" value="Preview" />
<input type="submit" name="action" value="Save" />
<input type="submit" name="action" value="Cancel" />
and
self.br.select_form(name='my_form')
submit_response = self.br.submit(name='action', label='Preview')
self.br.back()
submit_response = self.br.submit(name='action', label='Save')
IMPORTANT NOTE - I was only able to get any of this multiple-submit-button code to work after cleaning up some HTML in the rest of the page.
Specifically, I could not have <br/> - instead I had to have <br /> ... and, making even less sense, I could not have anything between the two submit buttons.
It frustrated me to no end that the mechanize/ClientForm bug I hunted for over two hours boiled down to this:
<tr><td colspan="2"><br/><input type="submit" name="Preview" value="Preview" /> <input type="submit" name="Create" value="Create New Page" /></td></tr>
(all on one line) did not work, but
<tr><td colspan="2"><br />
<input type="submit" name="Preview" value="Preview" />
<input type="submit" name="Create" value="Create New Page" /></td></tr>
worked fine (on multiple lines, which also shouldn't have mattered).
I like mechanize because it was easy to install (just copy the files into my include directory) and because it's pretty simple to use, but unless I'm missing something major, I think that bugs like this are kind of awful - I can't think of a good reason at all why the first example there should fail and the second should work.
And, incidentally, I also found another mechanize bug where a <textarea> which is contained within a <p> is not recognized as a valid control, but once you take it out of the <p> container it's recognized just fine. And I checked, textarea is allowed to be included in other block-level elements like <p>.
|
How to access data when form.is_valid() is false
|
When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.
I'm trying to access forms within a form set, so form.data seems to just give me a mess.
|
You can use
form.data['field_name']
This way you get the raw value assigned to the field.
|
Static methods in Python?
|
Is it possible to have static methods in Python so I can call them without initializing a class, like:
ClassName.StaticMethod ( )
|
Yep, using the staticmethod decorator
class MyClass(object):
@staticmethod
def the_static_method(x):
print x
MyClass.the_static_method(2) # outputs 2
Note that some code might use the old method of defining a static method, using staticmethod as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)
class MyClass(object):
def the_static_method(x):
print x
the_static_method = staticmethod(the_static_method)
MyClass.the_static_method(2) # outputs 2
This is entirely identical to the first example (using @staticmethod), just not using the nice decorator syntax
Finally, use staticmethod() sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.
The following is verbatim from the documentation::
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C:
@staticmethod
def f(arg1, arg2, ...): ...
The @staticmethod form is a function decorator â see the description of function definitions in Function definitions for details.
It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.
Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod().
For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.
New in version 2.2.
Changed in version 2.4: Function decorator syntax added.
|
Checking if a string can be converted to float in Python
|
I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy
if element.isdigit():
newelement=int(element)
Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.
partition=element.partition('.')
if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''):
newelement=float(element)
This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in this question.
Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?
|
I would just use..
try:
float(element)
except ValueError:
print "Not a float"
..it's simple, and it works
Another option would be a regular expression:
import re
if re.match("^\d+?\.\d+?$", element) is None:
print "Not float"
|
How to read ID3 Tag in an MP3 using Python?
|
Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)
|
Dive into Python uses MP3 ID3 tags as an example.
|
In Python, how do I reference a class generically in a static way, like PHP's "self" keyword?
|
PHP classes can use the keyword "self" in a static context, like this:
<?php
class Test {
public static $myvar = 'a';
public static function t() {
echo self::$myvar; // Generically reference the current class.
echo Test::$myvar; // Same thing, but not generic.
}
}
?>
Obviously I can't use "self" in this way in Python because "self" refers not to a class but to an instance. So is there a way I can reference the current class in a static context in Python, similar to PHP's "self"?
I guess what I'm trying to do is rather un-pythonic. Not sure though, I'm new to Python. Here is my code (using the Django framework):
class Friendship(models.Model):
def addfriend(self, friend):
"""does some stuff"""
@staticmethod # declared "staticmethod", not "classmethod"
def user_addfriend(user, friend): # static version of above method
userf = Friendship(user=user) # creating instance of the current class
userf.addfriend(friend) # calls above method
# later ....
Friendship.user_addfriend(u, f) # works
My code works as expected. I just wanted to know: is there a keyword I could use on the first line of the static method instead of "Friendship"?
This way if the class name changes, the static method won't have to be edited. As it stands the static method would have to be edited if the class name changes.
|
In all cases, self.__class__ is an object's class.
http://docs.python.org/library/stdtypes.html#special-attributes
In the (very) rare case where you are trying to mess with static methods, you actually need classmethod for this.
class AllStatic( object ):
@classmethod
def aMethod( cls, arg ):
# cls is the owning class for this method
x = AllStatic()
x.aMethod( 3.14 )
|
Date Ordinal Output?
|
I'm wondering if there is a quick and easy way to output ordinals given a number in python.
For example, given the number 1, I'd like to output "1st", the number 2, "2nd", et cetera, et cetera.
This is for working with dates in a breadcrumb trail
Home > Venues > Bar Academy > 2009 > April > 01
is what is currently shown
I'd like to have something along the lines of
Home > Venues > Bar Academy > 2009 > April > 1st
|
Or shorten David's answer with:
if 4 <= day <= 20 or 24 <= day <= 30:
suffix = "th"
else:
suffix = ["st", "nd", "rd"][day % 10 - 1]
|
Customize/remove Django select box blank option
|
I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:
<option value="">---------</option>
What I'd like to know is:
What is the cleanest way to remove this auto-generated option from the select box?
What is the cleanest way to customize it so that it shows as:
<option value="">Select Item</option>
In searching for a solution I came across Django ticket 4653 which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.
Thanks for any help,
Jeff
Edit: I've configured the ForeignKey field as such:
verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.
|
Haven't tested this, but based on reading Django's code here and here I believe it should work:
class ThingForm(models.ModelForm):
class Meta:
model = Thing
def __init__(self, *args, **kwargs):
super(ThingForm, self).__init__(*args, **kwargs)
self.fields['verb'].empty_label = None
EDIT: This is documented, though you wouldn't necessarily know to look for ModelChoiceField if you're working with an auto-generated ModelForm.
EDIT: As jlpp notes in his answer, this isn't complete - you have to re-assign the choices to the widgets after changing the empty_label attribute. Since that's a bit hacky, the other option that might be easier to understand is just overriding the entire ModelChoiceField:
class ThingForm(models.ModelForm):
verb = ModelChoiceField(Verb.objects.all(), empty_label=None)
class Meta:
model = Thing
|
Easiest way to generate localization files
|
I'm currently writing an app in Python and need to provide localization for it.
I can use gettext and the utilities that come with it to generate .po and .mo files. But editing the .po files for each language, one-by-one, seems a bit tedious. Then, creating directories for each language and generating the .mo files, one-by-one, seems like overkill. The end result being something like:
/en_US/LC_MESSAGES/en_US.mo
/en_CA/LC_MESSAGES/en_CA.mo
etc.
I could be wrong, but it seems like there's got to be a better way to do this. Does anyone have any tools, tricks or general knowledge that I haven't found yet?
Thanks in advance!
EDIT: To be a little more clear, I'm looking for something that speeds up the process. since it's already pretty easy. For example, in .NET, I can generate all of the strings that need to be translated into an excel file. Then, translators can fill out the excel file and add columns for each language. Then, I can use xls2resx to generate the language resource files. Is there anything like that for gettext? I realize I could write a script to create and read from a csv and generate the files -- I was just hoping there is something already made.
|
I've just done this for a project I'm working on, for us the process is like this:
First, I have a POTFILES.in file which contains a list of source files needing translation. We actually have two files (e.g. admin.in and user.in), as the admin interface doesn't always need translating. So we can send translators only the file containing strings the users see.
Running the following command will create a .pot template from the POTFILES.in:
xgettext --files-from=POTFILES.in --directory=.. --output=messages.pot
Run the above command from the po/ directory, which should be a subdirectory of your project and contain the POTFILES.in file. The .pot file has the exact same format as a .po file, but it is a template containing no translations. You create a new template whenever new translatable strings have been added to your source files.
To update the already translated .po files and add new strings to them, run:
msgmerge --update --no-fuzzy-matching --backup=off da.po messages.pot
In the above example I disable fuzzy matching, as our strings are a mess and it did more harm than good. I also disabled backup files, as everything is in subversion here. Run the above command for each language, in this case I updated the danish translation.
Finally run msgfmt to create the .mo files from the .po files:
msgfmt nl.po --output-file nl.mo
Ofcourse, you wouldn't want to run this manually everytime, so create some scripts (or preferably one or more Makefiles) to do this for you.
Note that your directory layout is slightly different from my situation, so you will have to adjust output filenames/paths a bit, but the steps should be the same.
|
setattr with kwargs, pythonic or not?
|
I'm using __init__() like this in some SQLAlchemy ORM classes that have many parameters (upto 20).
def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
Is it "pythonic" to set attributes like this?
|
Yes. Another way to do this is.
def __init__(self, **kwargs):
self.__dict__.update( kwargs )
|
How to make a chain of function decorators in Python?
|
How can I make two decorators in Python that would do the following?
@makebold
@makeitalic
def say():
return "Hello"
...which should return:
"<b><i>Hello</i></b>"
I'm not trying to make HTML this way in a real application - just trying to understand how decorators and decorator chaining works.
|
If you are not into long explanations, see Paolo Bergantinoâs answer.
Decorator Basics
Pythonâs functions are objects
To understand decorators, you must first understand that functions are objects in Python. This has important consequences. Letâs see why with a simple example :
def shout(word="yes"):
return word.capitalize()+"!"
print(shout())
# outputs : 'Yes!'
# As an object, you can assign the function to a variable like any other object
scream = shout
# Notice we don't use parentheses: we are not calling the function, we are putting the function "shout" into the variable "scream". It means you can then call "shout" from "scream":
print(scream())
# outputs : 'Yes!'
# More than that, it means you can remove the old name 'shout', and the function will still be accessible from 'scream'
del shout
try:
print(shout())
except NameError, e:
print(e)
#outputs: "name 'shout' is not defined"
print(scream())
# outputs: 'Yes!'
Keep this in mind. Weâll circle back to it shortly.
Another interesting property of Python functions is they can be defined inside another function!
def talk():
# You can define a function on the fly in "talk" ...
def whisper(word="yes"):
return word.lower()+"..."
# ... and use it right away!
print(whisper())
# You call "talk", that defines "whisper" EVERY TIME you call it, then
# "whisper" is called in "talk".
talk()
# outputs:
# "yes..."
# But "whisper" DOES NOT EXIST outside "talk":
try:
print(whisper())
except NameError, e:
print(e)
#outputs : "name 'whisper' is not defined"*
#Python's functions are objects
Functions references
Okay, still here? Now the fun part...
Youâve seen that functions are objects. Therefore, functions:
can be assigned to a variable
can be defined in another function
That means that a function can return another function.
def getTalk(kind="shout"):
# We define functions on the fly
def shout(word="yes"):
return word.capitalize()+"!"
def whisper(word="yes") :
return word.lower()+"...";
# Then we return one of them
if kind == "shout":
# We don't use "()", we are not calling the function, we are returning the function object
return shout
else:
return whisper
# How do you use this strange beast?
# Get the function and assign it to a variable
talk = getTalk()
# You can see that "talk" is here a function object:
print(talk)
#outputs : <function shout at 0xb7ea817c>
# The object is the one returned by the function:
print(talk())
#outputs : Yes!
# And you can even use it directly if you feel wild:
print(getTalk("whisper")())
#outputs : yes...
Thereâs more!
If you can return a function, you can pass one as a parameter:
def doSomethingBefore(func):
print("I do something before then I call the function you gave me")
print(func())
doSomethingBefore(scream)
#outputs:
#I do something before then I call the function you gave me
#Yes!
Well, you just have everything needed to understand decorators. You see, decorators are âwrappersâ, which means that they let you execute code before and after the function they decorate without modifying the function itself.
Handcrafted decorators
How youâd do it manually:
# A decorator is a function that expects ANOTHER function as parameter
def my_shiny_new_decorator(a_function_to_decorate):
# Inside, the decorator defines a function on the fly: the wrapper.
# This function is going to be wrapped around the original function
# so it can execute code before and after it.
def the_wrapper_around_the_original_function():
# Put here the code you want to be executed BEFORE the original function is called
print("Before the function runs")
# Call the function here (using parentheses)
a_function_to_decorate()
# Put here the code you want to be executed AFTER the original function is called
print("After the function runs")
# At this point, "a_function_to_decorate" HAS NEVER BEEN EXECUTED.
# We return the wrapper function we have just created.
# The wrapper contains the function and the code to execute before and after. Itâs ready to use!
return the_wrapper_around_the_original_function
# Now imagine you create a function you don't want to ever touch again.
def a_stand_alone_function():
print("I am a stand alone function, don't you dare modify me")
a_stand_alone_function()
#outputs: I am a stand alone function, don't you dare modify me
# Well, you can decorate it to extend its behavior.
# Just pass it to the decorator, it will wrap it dynamically in
# any code you want and return you a new function ready to be used:
a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function_decorated()
#outputs:
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs
Now, you probably want that every time you call a_stand_alone_function, a_stand_alone_function_decorated is called instead. Thatâs easy, just overwrite a_stand_alone_function with the function returned by my_shiny_new_decorator:
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
#outputs:
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs
# Thatâs EXACTLY what decorators do!
Decorators demystified
The previous example, using the decorator syntax:
@my_shiny_new_decorator
def another_stand_alone_function():
print("Leave me alone")
another_stand_alone_function()
#outputs:
#Before the function runs
#Leave me alone
#After the function runs
Yes, thatâs all, itâs that simple. @decorator is just a shortcut to:
another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)
Decorators are just a pythonic variant of the decorator design pattern. There are several classic design patterns embedded in Python to ease development (like iterators).
Of course, you can accumulate decorators:
def bread(func):
def wrapper():
print("</''''''\>")
func()
print("<\______/>")
return wrapper
def ingredients(func):
def wrapper():
print("#tomatoes#")
func()
print("~salad~")
return wrapper
def sandwich(food="--ham--"):
print(food)
sandwich()
#outputs: --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>
Using the Python decorator syntax:
@bread
@ingredients
def sandwich(food="--ham--"):
print(food)
sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>
The order you set the decorators MATTERS:
@ingredients
@bread
def strange_sandwich(food="--ham--"):
print(food)
strange_sandwich()
#outputs:
##tomatoes#
#</''''''\>
# --ham--
#<\______/>
# ~salad~
Now: to answer the question...
As a conclusion, you can easily see how to answer the question:
# The decorator to make it bold
def makebold(fn):
# The new function the decorator returns
def wrapper():
# Insertion of some code before and after
return "<b>" + fn() + "</b>"
return wrapper
# The decorator to make it italic
def makeitalic(fn):
# The new function the decorator returns
def wrapper():
# Insertion of some code before and after
return "<i>" + fn() + "</i>"
return wrapper
@makebold
@makeitalic
def say():
return "hello"
print(say())
#outputs: <b><i>hello</i></b>
# This is the exact equivalent to
def say():
return "hello"
say = makebold(makeitalic(say))
print(say())
#outputs: <b><i>hello</i></b>
You can now just leave happy, or burn your brain a little bit more and see advanced uses of decorators.
Taking decorators to the next level
Passing arguments to the decorated function
# Itâs not black magic, you just have to let the wrapper
# pass the argument:
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(arg1, arg2):
print("I got args! Look: {0}, {1}".format(arg1, arg2))
function_to_decorate(arg1, arg2)
return a_wrapper_accepting_arguments
# Since when you are calling the function returned by the decorator, you are
# calling the wrapper, passing arguments to the wrapper will let it pass them to
# the decorated function
@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
print("My name is {0} {1}".format(first_name, last_name))
print_full_name("Peter", "Venkman")
# outputs:
#I got args! Look: Peter Venkman
#My name is Peter Venkman
Decorating methods
One nifty thing about Python is that methods and functions are really the same. The only difference is that methods expect that their first argument is a reference to the current object (self).
That means you can build a decorator for methods the same way! Just remember to take self into consideration:
def method_friendly_decorator(method_to_decorate):
def wrapper(self, lie):
lie = lie - 3 # very friendly, decrease age even more :-)
return method_to_decorate(self, lie)
return wrapper
class Lucy(object):
def __init__(self):
self.age = 32
@method_friendly_decorator
def sayYourAge(self, lie):
print("I am {0}, what did you think?".format(self.age + lie))
l = Lucy()
l.sayYourAge(-3)
#outputs: I am 26, what did you think?
If youâre making general-purpose decorator--one youâll apply to any function or method, no matter its arguments--then just use *args, **kwargs:
def a_decorator_passing_arbitrary_arguments(function_to_decorate):
# The wrapper accepts any arguments
def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
print("Do I have args?:")
print(args)
print(kwargs)
# Then you unpack the arguments, here *args, **kwargs
# If you are not familiar with unpacking, check:
# http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
function_to_decorate(*args, **kwargs)
return a_wrapper_accepting_arbitrary_arguments
@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():
print("Python is cool, no argument here.")
function_with_no_argument()
#outputs
#Do I have args?:
#()
#{}
#Python is cool, no argument here.
@a_decorator_passing_arbitrary_arguments
def function_with_arguments(a, b, c):
print(a, b, c)
function_with_arguments(1,2,3)
#outputs
#Do I have args?:
#(1, 2, 3)
#{}
#1 2 3
@a_decorator_passing_arbitrary_arguments
def function_with_named_arguments(a, b, c, platypus="Why not ?"):
print("Do {0}, {1} and {2} like platypus? {3}".format(a, b, c, platypus))
function_with_named_arguments("Bill", "Linus", "Steve", platypus="Indeed!")
#outputs
#Do I have args ? :
#('Bill', 'Linus', 'Steve')
#{'platypus': 'Indeed!'}
#Do Bill, Linus and Steve like platypus? Indeed!
class Mary(object):
def __init__(self):
self.age = 31
@a_decorator_passing_arbitrary_arguments
def sayYourAge(self, lie=-3): # You can now add a default value
print("I am {0}, what did you think?".format(self.age + lie))
m = Mary()
m.sayYourAge()
#outputs
# Do I have args?:
#(<__main__.Mary object at 0xb7d303ac>,)
#{}
#I am 28, what did you think?
Passing arguments to the decorator
Great, now what would you say about passing arguments to the decorator itself?
This can get somewhat twisted, since a decorator must accept a function as an argument. Therefore, you cannot pass the decorated functionâs arguments directly to the decorator.
Before rushing to the solution, letâs write a little reminder:
# Decorators are ORDINARY functions
def my_decorator(func):
print("I am an ordinary function")
def wrapper():
print("I am function returned by the decorator")
func()
return wrapper
# Therefore, you can call it without any "@"
def lazy_function():
print("zzzzzzzz")
decorated_function = my_decorator(lazy_function)
#outputs: I am an ordinary function
# It outputs "I am an ordinary function", because thatâs just what you do:
# calling a function. Nothing magic.
@my_decorator
def lazy_function():
print("zzzzzzzz")
#outputs: I am an ordinary function
Itâs exactly the same. "my_decorator" is called. So when you @my_decorator, you are telling Python to call the function 'labelled by the variable "my_decorator"'.
This is important! The label you give can point directly to the decoratorâor not.
Letâs get evil. âº
def decorator_maker():
print("I make decorators! I am executed only once: "
"when you make me create a decorator.")
def my_decorator(func):
print("I am a decorator! I am executed only when you decorate a function.")
def wrapped():
print("I am the wrapper around the decorated function. "
"I am called when you call the decorated function. "
"As the wrapper, I return the RESULT of the decorated function.")
return func()
print("As the decorator, I return the wrapped function.")
return wrapped
print("As a decorator maker, I return a decorator")
return my_decorator
# Letâs create a decorator. Itâs just a new function after all.
new_decorator = decorator_maker()
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
# Then we decorate the function
def decorated_function():
print("I am the decorated function.")
decorated_function = new_decorator(decorated_function)
#outputs:
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function
# Letâs call the function:
decorated_function()
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.
No surprise here.
Letâs do EXACTLY the same thing, but skip all the pesky intermediate variables:
def decorated_function():
print("I am the decorated function.")
decorated_function = decorator_maker()(decorated_function)
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function.
# Finally:
decorated_function()
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.
Letâs make it even shorter:
@decorator_maker()
def decorated_function():
print("I am the decorated function.")
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function.
#Eventually:
decorated_function()
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.
Hey, did you see that? We used a function call with the "@" syntax! :-)
So, back to decorators with arguments. If we can use functions to generate the decorator on the fly, we can pass arguments to that function, right?
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):
print("I make decorators! And I accept arguments: {0}, {1}".format(decorator_arg1, decorator_arg2))
def my_decorator(func):
# The ability to pass arguments here is a gift from closures.
# If you are not comfortable with closures, you can assume itâs ok,
# or read: http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
print("I am the decorator. Somehow you passed me arguments: {0}, {1}".format(decorator_arg1, decorator_arg2))
# Don't confuse decorator arguments and function arguments!
def wrapped(function_arg1, function_arg2) :
print("I am the wrapper around the decorated function.\n"
"I can access all the variables\n"
"\t- from the decorator: {0} {1}\n"
"\t- from the function call: {2} {3}\n"
"Then I can pass them to the decorated function"
.format(decorator_arg1, decorator_arg2,
function_arg1, function_arg2))
return func(function_arg1, function_arg2)
return wrapped
return my_decorator
@decorator_maker_with_arguments("Leonard", "Sheldon")
def decorated_function_with_arguments(function_arg1, function_arg2):
print("I am the decorated function and only knows about my arguments: {0}"
" {1}".format(function_arg1, function_arg2))
decorated_function_with_arguments("Rajesh", "Howard")
#outputs:
#I make decorators! And I accept arguments: Leonard Sheldon
#I am the decorator. Somehow you passed me arguments: Leonard Sheldon
#I am the wrapper around the decorated function.
#I can access all the variables
# - from the decorator: Leonard Sheldon
# - from the function call: Rajesh Howard
#Then I can pass them to the decorated function
#I am the decorated function and only knows about my arguments: Rajesh Howard
Here it is: a decorator with arguments. Arguments can be set as variable:
c1 = "Penny"
c2 = "Leslie"
@decorator_maker_with_arguments("Leonard", c1)
def decorated_function_with_arguments(function_arg1, function_arg2):
print("I am the decorated function and only knows about my arguments:"
" {0} {1}".format(function_arg1, function_arg2))
decorated_function_with_arguments(c2, "Howard")
#outputs:
#I make decorators! And I accept arguments: Leonard Penny
#I am the decorator. Somehow you passed me arguments: Leonard Penny
#I am the wrapper around the decorated function.
#I can access all the variables
# - from the decorator: Leonard Penny
# - from the function call: Leslie Howard
#Then I can pass them to the decorated function
#I am the decorated function and only knows about my arguments: Leslie Howard
As you can see, you can pass arguments to the decorator like any function using this trick. You can even use *args, **kwargs if you wish. But remember decorators are called only once. Just when Python imports the script. You can't dynamically set the arguments afterwards. When you do "import x", the function is already decorated, so you can't
change anything.
Letâs practice: decorating a decorator
Okay, as a bonus, I'll give you a snippet to make any decorator accept generically any argument. After all, in order to accept arguments, we created our decorator using another function.
We wrapped the decorator.
Anything else we saw recently that wrapped function?
Oh yes, decorators!
Letâs have some fun and write a decorator for the decorators:
def decorator_with_args(decorator_to_enhance):
"""
This function is supposed to be used as a decorator.
It must decorate an other function, that is intended to be used as a decorator.
Take a cup of coffee.
It will allow any decorator to accept an arbitrary number of arguments,
saving you the headache to remember how to do that every time.
"""
# We use the same trick we did to pass arguments
def decorator_maker(*args, **kwargs):
# We create on the fly a decorator that accepts only a function
# but keeps the passed arguments from the maker.
def decorator_wrapper(func):
# We return the result of the original decorator, which, after all,
# IS JUST AN ORDINARY FUNCTION (which returns a function).
# Only pitfall: the decorator must have this specific signature or it won't work:
return decorator_to_enhance(func, *args, **kwargs)
return decorator_wrapper
return decorator_maker
It can be used as follows:
# You create the function you will use as a decorator. And stick a decorator on it :-)
# Don't forget, the signature is "decorator(func, *args, **kwargs)"
@decorator_with_args
def decorated_decorator(func, *args, **kwargs):
def wrapper(function_arg1, function_arg2):
print("Decorated with {0} {1}".format(args, kwargs))
return func(function_arg1, function_arg2)
return wrapper
# Then you decorate the functions you wish with your brand new decorated decorator.
@decorated_decorator(42, 404, 1024)
def decorated_function(function_arg1, function_arg2):
print("Hello {0} {1}".format(function_arg1, function_arg2))
decorated_function("Universe and", "everything")
#outputs:
#Decorated with (42, 404, 1024) {}
#Hello Universe and everything
# Whoooot!
I know, the last time you had this feeling, it was after listening a guy saying: "before understanding recursion, you must first understand recursion". But now, don't you feel good about mastering this?
Best practices: decorators
Decorators were introduced in Python 2.4, so be sure your code will be run on >= 2.4.
Decorators slow down the function call. Keep that in mind.
You cannot un-decorate a function. (There are hacks to create decorators that can be removed, but nobody uses them.) So once a function is decorated, itâs decorated for all the code.
Decorators wrap functions, which can make them hard to debug. (This gets better from Python >= 2.5; see below.)
The functools module was introduced in Python 2.5. It includes the function functools.wraps(), which copies the name, module, and docstring of the decorated function to its wrapper.
(Fun fact: functools.wraps() is a decorator! âº)
# For debugging, the stacktrace prints you the function __name__
def foo():
print("foo")
print(foo.__name__)
#outputs: foo
# With a decorator, it gets messy
def bar(func):
def wrapper():
print("bar")
return func()
return wrapper
@bar
def foo():
print("foo")
print(foo.__name__)
#outputs: wrapper
# "functools" can help for that
import functools
def bar(func):
# We say that "wrapper", is wrapping "func"
# and the magic begins
@functools.wraps(func)
def wrapper():
print("bar")
return func()
return wrapper
@bar
def foo():
print("foo")
print(foo.__name__)
#outputs: foo
How can the decorators be useful?
Now the big question: What can I use decorators for?
Seem cool and powerful, but a practical example would be great. Well, there are 1000 possibilities. Classic uses are extending a function behavior from an external lib (you can't modify it), or for debugging (you don't want to modify it because itâs temporary).
You can use them to extend several functions in a DRYâs way, like so:
def benchmark(func):
"""
A decorator that prints the time a function takes
to execute.
"""
import time
def wrapper(*args, **kwargs):
t = time.clock()
res = func(*args, **kwargs)
print("{0} {1}".format(func.__name__, time.clock()-t))
return res
return wrapper
def logging(func):
"""
A decorator that logs the activity of the script.
(it actually just prints it, but it could be logging!)
"""
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
print("{0} {1} {2}".format(func.__name__, args, kwargs))
return res
return wrapper
def counter(func):
"""
A decorator that counts and prints the number of times a function has been executed
"""
def wrapper(*args, **kwargs):
wrapper.count = wrapper.count + 1
res = func(*args, **kwargs)
print("{0} has been used: {1}x".format(func.__name__, wrapper.count))
return res
wrapper.count = 0
return wrapper
@counter
@benchmark
@logging
def reverse_string(string):
return str(reversed(string))
print(reverse_string("Able was I ere I saw Elba"))
print(reverse_string("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!"))
#outputs:
#reverse_string ('Able was I ere I saw Elba',) {}
#wrapper 0.0
#wrapper has been used: 1x
#ablE was I ere I saw elbA
#reverse_string ('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!',) {}
#wrapper 0.0
#wrapper has been used: 2x
#!amanaP :lanac a ,noep a ,stah eros ,raj a ,hsac ,oloR a ,tur a ,mapS ,snip ,eperc a ,)lemac a ro( niaga gab ananab a ,gat a ,nat a ,gab ananab a ,gag a ,inoracam ,elacrep ,epins ,spam ,arutaroloc a ,shajar ,soreh ,atsap ,eonac a ,nalp a ,nam A
Of course the good thing with decorators is that you can use them right away on almost anything without rewriting. DRY, I said:
@counter
@benchmark
@logging
def get_random_futurama_quote():
from urllib import urlopen
result = urlopen("http://subfusion.net/cgi-bin/quote.pl?quote=futurama").read()
try:
value = result.split("<br><b><hr><br>")[1].split("<br><br><hr>")[0]
return value.strip()
except:
return "No, I'm ... doesn't!"
print(get_random_futurama_quote())
print(get_random_futurama_quote())
#outputs:
#get_random_futurama_quote () {}
#wrapper 0.02
#wrapper has been used: 1x
#The laws of science be a harsh mistress.
#get_random_futurama_quote () {}
#wrapper 0.01
#wrapper has been used: 2x
#Curse you, merciful Poseidon!
Python itself provides several decorators: property, staticmethod, etc.
Django uses decorators to manage caching and view permissions.
Twisted to fake inlining asynchronous functions calls.
This really is a large playground.
|
Iterating over object instances of a given class in Python
|
Given a class that keeps a registry of its Objects:
class Person(object):
__registry = []
def __init__(self, name):
self.__registry.append(self)
self.name = name
How would I make the following code work (without using Person.__registry):
for personobject in Person:
print personobject
While researching I found a hint that one could go for a __metaclass__ with a __getitem__-method. Any ideas how this would look like?
|
You can make your class object iterable with a simple metaclass.
class IterRegistry(type):
def __iter__(cls):
return iter(cls._registry)
class Person(object):
__metaclass__ = IterRegistry
_registry = []
def __init__(self, name):
self._registry.append(self)
self.name = name
(I have also changed __registry to _registry to make it easier to access from the metaclass).
Then,
>>> p = Person('John')
>>> p2 = Person('Mary')
>>> for personobject in Person:
... print personobject
...
<person.Person object at 0x70410>
<person.Person object at 0x70250>
|
How can I get a list of locally installed Python modules?
|
I would like to get a list of Python modules, which are in my Python installation (UNIX server).
How can you get a list of Python modules installed in your computer?
|
help('modules')
in a Python shell/prompt.
|
How to check if one of the following items is in a list?
|
I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.
>>> a = [2,3,4]
>>> print (1 or 2) in a
False
>>> print (2 or 1) in a
True
|
>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i in L2]
[2]
>>> S1 = set(L1)
>>> S2 = set(L2)
>>> S1.intersection(S2)
set([2])
Both empty lists and empty sets are False, so you can use the value directly as a truth value.
|
python write string directly to tarfile
|
Is there a way to write a string directly to a tarfile? From http://docs.python.org/library/tarfile.html it looks like only files already written to the file system can be added.
|
I would say it's possible, by playing with TarInfo e TarFile.addfile passing a StringIO as a fileobject.
Very rough, but works
import tarfile
import StringIO
tar = tarfile.TarFile("test.tar","w")
string = StringIO.StringIO()
string.write("hello")
string.seek(0)
info = tarfile.TarInfo(name="foo")
info.size=len(string.buf)
tar.addfile(tarinfo=info, fileobj=string)
tar.close()
|
How do I tell matplotlib that I am done with a plot?
|
The following code plots to two PostScript (.ps) files, but the second one contains both lines.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(111)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")
plt.subplot(111)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
How can I tell matplotlib to start afresh for the second plot?
|
There is a clear figure command, and it should do it for you:
plt.clf()
If you have multiple subplots in the same figure
plt.cla()
clears the current axes.
|
Programatically determining amount of parameters a function requires - Python
|
I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form {Keyword:(FunctionName, AmountofArguments)}.
This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.
Thanks for any help.
|
inspect.getargspec():
Get the names and default values of a functionâs arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.
|
Emulate a do-while loop in Python?
|
I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
l = [ 1, 2, 3 ]
i = l.__iter__()
s = None
while True :
if s :
print s
try :
s = i.next()
except StopIteration :
break
print "done"
Instead of "1,2,3,done", it prints the following output:
[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', ' File "test_python.py", line 8, in <module>
s = i.next()
', 'StopIteration
']
What can I do in order to catch the 'stop iteration' exception and break a while
loop properly?
An example of why such a thing may be needed is shown below as pseudocode.
State machine:
s = ""
while True :
if state is STATE_CODE :
if "//" in s :
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT :
if "//" in s :
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
else
state = STATE_CODE
# Re-evaluate same line
continue
try :
s = i.next()
except StopIteration :
break
|
I am not sure what you are trying to do. You can implement a do-while loop like this:
while True:
stuff()
if fail_condition:
break
Or:
stuff()
while not fail_condition:
stuff()
What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:
for i in l:
print i
print "done"
Update:
So do you have a list of lines? And you want to keep iterating through it? How about:
for s in l:
while True:
stuff()
# use a "break" instead of s = i.next()
Does that seem like something close to what you would want? With your code example, it would be:
for s in some_list:
while True :
if state is STATE_CODE :
if "//" in s :
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT :
if "//" in s :
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
break # get next s
else
state = STATE_CODE
# re-evaluate same line
# continues automatically
|
Split string into a list in Python
|
I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?
def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(word)
|
Splits the string in text on delimiter: " ".
words = text.split()
Split the string in text on delimiter: ",".
words = text.split(",")
The words variable will be a list datatype and contain a list of words from text split on the delimiter.
|
Reading Huge File in Python
|
I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.
My current approach is included below. It takes 30 seconds. There must be more efficient Python foo to get this down to a reasonable efficiency of a couple of seconds at most.
# list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
Coded binary search + seek solution (thanks kigurai!):
entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search
|
If you only need 200 of 50 million lines, then reading all of it into memory is a waste. I would sort the list of search keys and then apply binary search to the file using seek() or something similar. This way you would not read the entire file to memory which I think should speed things up.
|
Circular (or cyclic) imports in Python
|
What will happen if two modules import each other?
To generalize the problem, what about the cyclic imports in Python?
|
There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.
Imports are pretty straightforward really. Just remember the following:
'import' and 'from xxx import yyy' are executable statements. They execute
when the running program reaches that line.
If a module is not in sys.modules, then an import creates the new module
entry in sys.modules and then executes the code in the module. It does not
return control to the calling module until the execution has completed.
If a module does exist in sys.modules then an import simply returns that
module whether or not it has completed executing. That is the reason why
cyclic imports may return modules which appear to be partly empty.
Finally, the executing script runs in a module named __main__, importing
the script under its own name will create a new module unrelated to
__main__.
Take that lot together and you shouldn't get any surprises when importing
modules.
|
Is Python interpreted (like Javascript or PHP)?
|
Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?
|
As the varied responses will tell you, the line between interpreted and compiled is no longer as clear as it was when such terms were coined. In fact, it's also something of a mistake to consider languages as being either interpreted or compiled, as different implementations of languages may do different things. These days you can find both C interpreters and Javascript compilers.
Even when looking at an implementation, things still aren't clear-cut. There are layers of interpretation. Here are a few of the gradations between interpreted and compiled:
Pure interpretation. Pretty much what it says on the tin. Read a line of source and immediately do what it says. This isn't actually done by many production languages - pretty much just things like shell scripts.
Tokenisation + interpretation. A trivial optimisation on the above. Rather than interpret each line from scratch, it's first tokenised (that is, rather than seeing a string like "print 52 + x", it's translated into a stream of tokens (eg. [PRINT_STATEMENT, INTEGER(52), PLUS_SIGN, IDENTIFIER('x')] ) to avoid repeatedly performing that state of interpretation. Many versions of basic worked this way.
Bytecode compilation. This is the approach taken by languages like Java and C# (though see below). The code is transformed into instructions for a "virtual machine". These instructions are then interpreted. This is also the approach taken by python (or at least cpython, the most common implementation.) The Jython and Ironpython implementations also take this approach, but compile to the bytecode for the Java and C# virtual machines resepectively.
Bytecode + Just in Time compilation. As above, but rather than interpreting the bytecodes, the code that would be performed is compiled from the bytecode at the point of execution, and then run. In some cases, this can actually outperform native compilation, as it is free to perform runtime analysis on the code, and can use specific features of the current processor (while static compilation may need to compile for a lowest common denominator CPU). Later versions of Java, and C# use this approach. Psyco performs this for python.
Native machine-code compilation. The code is compiled to the machine code of the target system. You may think we've now completely eliminated interpretation, but even here there are subtleties. Some machine code instructions are not actually directly implemented in hardware, but are in fact implemented via microcode - even machine code is sometimes interpreted!
|
wxPython: Calling an event manually
|
How can I call a specific event manually from my own code?
|
Old topic, but I think I've got this figured out after being confused about it for a long time, so if anyone else comes through here looking for the answer, this might help.
To manually post an event, you can use
self.GetEventHandler().ProcessEvent(event)
(wxWidgets docs here, wxPython docs here)
or
wx.PostEvent(self.GetEventHandler(), event)
(wxWidgets docs, wxPython docs)
where event is the event you want to post. Construct the event with e.g.
wx.PyCommandEvent(wx.EVT_BUTTON.typeId, self.GetId())
if you want to post a EVT_BUTTON event. Making it a PyCommandEvent means that it will propagate upwards; other event types don't propagate by default.
You can also create custom events that can carry whatever data you want them to. Here's an example:
myEVT_CUSTOM = wx.NewEventType()
EVT_CUSTOM = wx.PyEventBinder(myEVT_CUSTOM, 1)
class MyEvent(wx.PyCommandEvent):
def __init__(self, evtType, id):
wx.PyCommandEvent.__init__(self, evtType, id)
myVal = None
def SetMyVal(self, val):
self.myVal = val
def GetMyVal(self):
return self.myVal
(I think I found this code in a mailing list archive somewhere, but I can't seem to find it again. If this is your example, thanks! Please add a comment and take credit for it!)
So now, to Post a custom event:
event = MyEvent(myEVT_CUSTOM, self.GetId())
event.SetMyVal('here is some custom data')
self.GetEventHandler().ProcessEvent(event)
and you can bind it just like any other event
self.Bind(EVT_CUSTOM, self.on_event)
and get the custom data in the event handler
def on_event(self, e):
data = e.GetMyVal()
print 'custom data is: {0}'.format(data)
Or include the custom data in the event constructor and save a step:
class MyEvent(wx.PyCommandEvent):
def __init__(self, evtType, id, val = None):
wx.PyCommandEvent.__init__(self, evtType, id)
self.myVal = val
etc.
Hope this is helpful to someone.
|
benchmarking django apps
|
I'm interested in testing the performance of my django apps as I go, what is the best way to get line by line performance data?
note: Googling this returns lots of people benchmarking django itself. I'm not looking for a benchmarks of django, I'm trying to test the performance of the django apps that I'm writing :)
Thanks!
edit: By "line by line" I just mean timing individual functions, db calls, etc to find out where the bottlenecks are on a very granular level
|
There's two layers to this. We have most of #1 in place for our testing. We're about to start on #2.
Django in isolation. The ordinary Django unit tests works well here. Create some tests that cycle through a few (less than 6) "typical" use cases. Get this, post that, etc. Collect timing data. This isn't real web performance, but it's an easy-to-work with test scenario that you can use for tuning.
Your whole web stack. In this case, you need a regular server running Squid, Apache, Django, MySQL, whatever. You need a second computer(s) to act a client exercise your web site through urllib2, doing a few (less than 6) "typical" use cases. Get this, post that, etc. Collect timing data. This still isn't "real" web performance, because it isn't through the internet, but it's as close as you're going to get without a really elaborate setup.
Note that the #2 (end-to-end) includes a great deal of caching for performance. If your client scripts are doing similar work, caching will be really beneficial. if your client scripts do unique things each time, caching will be less beneficial.
The hardest part is determining what the "typical" workload is. This isn't functional testing, so the workload doesn't have to include everything. Also, the more concurrent sessions your client is running, the slower it becomes. Don't struggle trying to optimize your server when your test client is the slowest part of the processing.
Edit
If "line-by-line" means "profiling", well, you've got to get a Python profiler running.
https://docs.python.org/library/profile.html
Note that there's plenty of caching in the Django ORM layer. So running a view function a half-dozen times to get a meaningful set of measurements isn't sensible. You have to run a "typical" set of operations and then find hot-spots in the profile.
Generally, your application is easy to optimize -- you shouldn't be doing much. Your view functions should be short and have no processing to speak of. Your form and model method functions, similarly, should be very short.
|
Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS
|
I am just learning python and is interested in how this can be accomplished. During the search for the answer, I came across this service: http://www.longurlplease.com
For example:
http://bit.ly/rgCbf can be converted to:
http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place
I did some inspecting with Firefox and see that the original url is not in the header.
|
Enter urllib2, which offers the easiest way of doing this:
>>> import urllib2
>>> fp = urllib2.urlopen('http://bit.ly/rgCbf')
>>> fp.geturl()
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'
For reference's sake, however, note that this is also possible with httplib:
>>> import httplib
>>> conn = httplib.HTTPConnection('bit.ly')
>>> conn.request('HEAD', '/rgCbf')
>>> response = conn.getresponse()
>>> response.getheader('location')
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'
And with PycURL, although I'm not sure if this is the best way to do it using it:
>>> import pycurl
>>> conn = pycurl.Curl()
>>> conn.setopt(pycurl.URL, "http://bit.ly/rgCbf")
>>> conn.setopt(pycurl.FOLLOWLOCATION, 1)
>>> conn.setopt(pycurl.CUSTOMREQUEST, 'HEAD')
>>> conn.setopt(pycurl.NOBODY, True)
>>> conn.perform()
>>> conn.getinfo(pycurl.EFFECTIVE_URL)
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'
|
How do I create a datetime in Python from milliseconds?
|
I can create a similar Date object in Java by java.util.Date(milliseconds). How do I create the comparable in Python?
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
|
Just convert it to timestamp
datetime.datetime.fromtimestamp(ms/1000.0)
|
Finding duplicate files and removing them
|
I am writing a Python program to find and remove duplicate files from a folder.
I have multiple copies of mp3 files, and some other files. I am using the sh1 algorithm.
How can I find these duplicate files and remove them?
|
Recursive folders version:
This version uses the file size and a hash of the contents to find duplicates.
You can pass it multiple paths, it will scan all paths recursively and report all duplicates found.
import sys
import os
import hashlib
def chunk_reader(fobj, chunk_size=1024):
"""Generator that reads a file in chunks of bytes"""
while True:
chunk = fobj.read(chunk_size)
if not chunk:
return
yield chunk
def check_for_duplicates(paths, hash=hashlib.sha1):
hashes = {}
for path in paths:
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
hashobj = hash()
for chunk in chunk_reader(open(full_path, 'rb')):
hashobj.update(chunk)
file_id = (hashobj.digest(), os.path.getsize(full_path))
duplicate = hashes.get(file_id, None)
if duplicate:
print "Duplicate found: %s and %s" % (full_path, duplicate)
else:
hashes[file_id] = full_path
if sys.argv[1:]:
check_for_duplicates(sys.argv[1:])
else:
print "Please pass the paths to check as parameters to the script"
|
Partial list unpack in Python
|
In Python, the assignment operator can unpack list or tuple into variables, like this:
l = (1, 2)
a, b = l # Here goes auto unpack
But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the list to the right, for example if I use split(). Example:
a, b = "length=25".split("=") # This will result in a="length" and b=25
But the following code will lead to an error:
a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item
Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:
a = b = None
if "=" in string :
a, b = string.split("=")
else :
a = string
|
This may be of no use to you unless you're using Python 3. However, for completeness, it's worth noting that the extended tuple unpacking introduced there allows you to do things like:
>>> a, *b = "length=25".split("=")
>>> a,b
("length", ['25'])
>>> a, *b = "DEFAULT_LENGTH".split("=")
>>> a,b
("DEFAULT_LENGTH", [])
I.e. tuple unpacking now works similarly to how it does in argument unpacking, so you can denote "the rest of the items" with *, and get them as a (possibly empty) list.
Partition is probably the best solution for what you're doing however.
|
Search a list of strings for any sub-string from another list
|
Given these 3 lists of data and a list of keywords:
good_data1 = ['hello, world', 'hey, world']
good_data2 = ['hey, man', 'whats up']
bad_data = ['hi, earth', 'sup, planet']
keywords = ['world', 'he']
I'm trying to write a simple function to check if any of the keywords exist as a substring of any word in the data lists. It should return True for the good_data lists and False for bad_data.
I know how to do this in what seems to be an inefficient way:
def checkData(data):
for s in data:
for k in keywords:
if k in s:
return True
return False
|
Are you looking for
any( k in s for k in keywords )
It's more compact, but might be less efficient.
|
Python: How to estimate / calculate memory footprint of data structures?
|
What's a good way to estimate the memory footprint of an object?
Conversely, what's a good way to measure the footprint?
For example, say I have a dictionary whose values are lists of integer,float tuples:
d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18) ]
I have 4G of physical memory and would like to figure out approximately how many rows (key:values) I can store in memory before I spill into swap. This is on linux/ubuntu 8.04 and OS X 10.5.6 .
Also, what's the best way to figure out the actual in-memory footprint of my program? How do I best figure out when it's exhausting physical memory and spilling?
|
Guppy has a nice memory profiler (Heapy):
>>> from guppy import hpy
>>> hp = hpy()
>>> hp.setrelheap() # ignore all existing objects
>>> d = {}
>>> d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18) ]
>>> hp.heap()
Partition of a set of 24 objects. Total size = 1464 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 2 8 676 46 676 46 types.FrameType
1 6 25 220 15 896 61 str
2 6 25 184 13 1080 74 tuple
...
Heapy is a little underdocumented, so you might have to dig through the web page or source code a little, but it's very powerful. There are also some articles which might be relevant.
|
What is the format in which Django passwords are stored in the database?
|
You know how django passwords are stored like this:
sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
and that is the "hashtype $salt $hash". My question is, how do they get the $hash? Is it the password and salt combined and then hashed or is something else entirely?
|
As always, use the source:
# root/django/trunk/django/contrib/auth/models.py
# snip
def get_hexdigest(algorithm, salt, raw_password):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or 'crypt').
"""
raw_password, salt = smart_str(raw_password), smart_str(salt)
if algorithm == 'crypt':
try:
import crypt
except ImportError:
raise ValueError('"crypt" password algorithm not supported in this environment')
return crypt.crypt(raw_password, salt)
if algorithm == 'md5':
return md5_constructor(salt + raw_password).hexdigest()
elif algorithm == 'sha1':
return sha_constructor(salt + raw_password).hexdigest()
raise ValueError("Got unknown password algorithm type in password.")
As we can see, the password digests are made by concatenating the salt with the password using the selected hashing algorithm. then the algorithm name, the original salt, and password hash are concatenated, separated by "$"s to form the digest.
# Also from root/django/trunk/django/contrib/auth/models.py
def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
"""
algo, salt, hsh = enc_password.split('$')
return hsh == get_hexdigest(algo, salt, raw_password)
To validate passwords django just verifies that the same salt and same password result in the same digest.
|
Pretty printing XML in Python
|
What is the best way (or even the various ways) to pretty print xml in Python?
|
import xml.dom.minidom
xml = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xml.toprettyxml()
|
How is returning the output of a function different than printing it?
|
In my previous question, Andrew Jaffe writes:
In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return something.
When you create autoparts() or splittext(), the idea is that this will be a function that you can call, and it can (and should) give something back.
Once you figure out the output that you want your function to have, you need to put it in a return statement.
def autoparts():
parts_dict = {}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
print(parts_dict)
>>> autoparts()
{'part A': 1, 'part B': 2, ...}
This function creates a dictionary, but it does not return something. However, since I added the print, the output of the function is shown when I run the function. What is the difference between returning something and printing it?
|
Print simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do:
def autoparts():
parts_dict={}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
return parts_dict
Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it. Such as:
my_auto_parts=autoparts()
print my_auto_parts['engine']
See what happened? autoparts() was called and it returned the parts_dict and we stored it into the my_auto_parts variable. Now we can use this variable to access the dictionary object and it continues to live even though the function call is over. We then printed out the object in the dictionary with the key 'engine'.
For a good tutorial, check out dive into python. It's free and very easy to follow.
|
Emacs - tab-completion of local Python variables
|
Is there a good emacs mode that will allow tab-completion of local python variables? I set up ipython.el but it will only tab-complete things in the scope of the interpreter. I'm looking for something that will let me tab-complete tokens in the local namespace of a function or file.
|
M-/ runs the command dabbrev-expand . This will complete local names in any mode.
Also I bind meta f1 to hippie expand from all open buffers. This is very useful for me.
;; Bind hippie-expand
(global-set-key [(meta f1)] (make-hippie-expand-function
'(try-expand-dabbrev-visible
try-expand-dabbrev
try-expand-dabbrev-all-buffers) t))
Hope this is useful.
|
Split list into smaller lists
|
I am looking for a way to easily split a python list in half.
So that if I have an array:
A = [0,1,2,3,4,5]
I would be able to get:
B = [0,1,2]
C = [3,4,5]
|
A = [1,2,3,4,5,6]
B = A[:len(A)/2]
C = A[len(A)/2:]
If you want a function:
def split_list(a_list):
half = len(a_list)/2
return a_list[:half], a_list[half:]
A = [1,2,3,4,5,6]
B, C = split_list(A)
|
Is it safe to rely on condition evaluation order in if statements?
|
Is it bad practice to use the following format when my_var can be None?
if my_var and 'something' in my_var:
#do something
*The issue is that 'something' in my_var will throw a TypeError if my_var is None.*
Or should I use:
if my_var:
if 'something' in my_var:
#do something
or
try:
if 'something' in my_var:
#do something
except TypeError:
pass
To rephrase the question, which of the above is the best practice in Python (if any)?
Alternatives are welcome!
|
It's safe to depend on the order of conditionals (Python reference here), specifically because of the problem you point out - it's very useful to be able to short-circuit evaluation that could cause problems in a string of conditionals.
This sort of code pops up in most languages:
IF exists(variable) AND variable.doSomething()
THEN ...
|
How to work with unicode in Python
|
I am trying to clean all of the HTML out of a string so the final output is a text file. I have some some research on the various 'converters' and am starting to lean towards creating my own dictionary for the entities and symbols and running a replace on the string. I am considering this because I want to automate the process and there is a lot of variability in the quality of the underlying html. To begin comparing the speed of my solution and one of the alternatives for example pyparsing I decided to test replace of \xa0 using the string method replace. I get a
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128)
The actual line of code was
s=unicodestring.replace('\xa0','')
Anyway-I decided that I needed to preface it with an r so I ran this line of code:
s=unicodestring.replace(r'\xa0','')
It runs without error but I when I look at a slice of s I see that the \xaO is still there
|
may be you should be doing
s=unicodestring.replace(u'\xa0',u'')
|
Strip HTML from strings in Python
|
from mechanize import Browser
br = Browser()
br.open('http://somewebpage')
html = br.response().readlines()
for line in html:
print line
When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds '<a href="whatever.com">some text</a>', it will only print 'some text', '<b>hello</b>' prints 'hello', etc. How would one go about doing this?
|
I always used this function to strip HTML tags, as it requires only the Python stdlib:
On Python 2
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
For Python 3
from html.parser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.strict = False
self.convert_charrefs= True
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
Note: this works only for 3.1. For 3.2 or above, you need to call the parent class's init function. See Using HTMLParser in Python 3.2
|
Programmatically generate video or animated GIF in Python?
|
I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?
Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/
|
As of June 2009 the originally cited blog post has a method to create animated GIFs in the comments. Download the script images2gif.py (formerly images2gif.py, update courtesy of @geographika).
Then, to reverse the frames in a gif, for instance:
#!/usr/bin/env python
from PIL import Image, ImageSequence
import sys, os
filename = sys.argv[1]
im = Image.open(filename)
original_duration = im.info['duration']
frames = [frame.copy() for frame in ImageSequence.Iterator(im)]
frames.reverse()
from images2gif import writeGif
writeGif("reverse_" + os.path.basename(filename), frames, duration=original_duration/1000.0, dither=0)
|
Inheritance and Overriding __init__ in python
|
I was reading 'Dive Into Python' and in the chapter on classes it gives this example:
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
The author then says that if you want to override the __init__ method, you must explicitly call the parent __init__ with the correct parameters.
What if that FileInfo class had more than one ancestor class?
Do I have to explicitly call all of the ancestor classes' __init__ methods?
Also, do I have to do this to any other method I want to override?
|
The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclass built-in classes.
It looks like this nowadays.
class FileInfo(dict):
"""store file metadata"""
def __init__(self, filename=None):
super( FileInfo, self ).__init__()
self["name"] = filename
Note the following.
We can directly subclass built-in classes, like dict, list, tuple, etc.
The super function handles tracking down this class's superclasses and calling functions in them appropriately.
|
What is the purpose of the sub-interpreter API in CPython?
|
I'm unclear on why the sub-interpreter API exists and why it's used in modules such as the mod_wsgi apache module. Is it mainly used for creating a security sandbox for different applications running within the same process, or is it a way to allow concurrency with multiple threads? Maybe both? Are there other purposes?
|
I imagine the purpose is to create separate python execution environments. For instance, mod_wsgi (Apache Python module) hosts a single python interpreter and then hosts multiple applications within sub-interpreters (in the default configuration).
Some key points from the documentation:
This is an (almost) totally separate environment for the execution of Python code. In particular, the new interpreter has separate, independent versions of all imported modules, including the fundamental modules __builtin__, __main__ and sys.
The table of loaded modules (sys.modules) and the module search path (sys.path) are also separate.
Because sub-interpreters (and the main interpreter) are part of the same process, the insulation between them isnât perfect â for example, using low-level file operations like os.close() they can (accidentally or maliciously) affect each otherâs open files.
Because of the way extensions are shared between (sub-)interpreters, some extensions may not work properly; this is especially likely when the extension makes use of (static) global variables, or when the extension manipulates its moduleâs dictionary after its initialization.
|
Default value for field in Django model
|
Suppose I have a model:
class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.CharField(max_length=10)
b = models.CharField(max_length=7)
Currently I am using the default admin to create/edit objects of this type.
How do I remove the field b from the admin so that each object cannot be created with a value, and rather will receive a default value of 0000000?
|
Set editable to False and default to your default value.
http://docs.djangoproject.com/en/dev/ref/models/fields/#editable
b = models.CharField(max_length=7, default='0000000', editable=False)
Also, your id field is unnecessary. Django will add it automatically.
|
Listing all permutations of a string/integer
|
A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.
Is there an example of how this is done and the logic behind solving such a problem?
I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.
|
First of all: it smells like recursion of course!
Since you also wanted to know the principle, I did my best to explain it human language. I think recursion is very easy most of the times. You only have to grasp two steps:
The first step
All the other steps (all with the same logic)
In human language:
In short:
1. The permutation of 1 element is one element.
2. The permutation of a set of elements is a list each of the elements, concatenated with every permutation of the other elements.
Example:
If the set just has one element -->
return it.
perm(a) -> a
If the set has two characters: for
each element in it: return the
element, with the permutation of the
rest of the elements added, like so:
perm(ab) ->
a + perm(b) -> ab
b + perm(a) -> ba
Further: for each character in the set: return a character, concatenated with a perumation of > the rest of the set
perm(abc) ->
a + perm(bc) --> abc, acb
b + perm(ac) --> bac, bca
c + perm(ab) --> cab, cba
perm(abc...z) -->
a + perm(...), b + perm(....)
....
I found the pseudocode on http://www.programmersheaven.com/mb/Algorithms/369713/369713/permutation-algorithm-help/:
makePermutations(permutation) {
if (length permutation < required length) {
for (i = min digit to max digit) {
if (i not in permutation) {
makePermutations(permutation+i)
}
}
}
else {
add permutation to list
}
}
C#
OK, and something more elaborate (and since it is tagged c #), from http://radio.weblogs.com/0111551/stories/2002/10/14/permutations.html :
Rather lengthy, but I decided to copy it anyway, so the post is not dependent on the original.
The function takes a string of characters, and writes down every possible permutation of that exact string, so for example, if "ABC" has been supplied, should spill out:
ABC, ACB, BAC, BCA, CAB, CBA.
Code:
class Program
{
private static void Swap(ref char a, ref char b)
{
if (a == b) return;
a ^= b;
b ^= a;
a ^= b;
}
public static void GetPer(char[] list)
{
int x = list.Length - 1;
GetPer(list, 0, x);
}
private static void GetPer(char[] list, int k, int m)
{
if (k == m)
{
Console.Write(list);
}
else
for (int i = k; i <= m; i++)
{
Swap(ref list[k], ref list[i]);
GetPer(list, k + 1, m);
Swap(ref list[k], ref list[i]);
}
}
static void Main()
{
string str = "sagiv";
char[] arr = str.ToCharArray();
GetPer(arr);
}
}
|
Multiple Tuple to Two-Pair Tuple in Python?
|
What is the nicest way of splitting this:
tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
into this:
tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
Assuming that the input always has an even number of values.
|
zip() is your friend:
t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip(t[::2], t[1::2])
|
Using multiple listboxes in python tkinter
|
from Tkinter import *
master = Tk()
listbox = Listbox(master)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
listbox2 = Listbox(master)
listbox2.pack()
listbox2.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox2.insert(END, item)
mainloop()
The code above creates a tkinter window with two listboxes. But there's a problem if you want to retrieve the values from both, because as soon as you select a value in one, it deselects whatever you selected in the other. Is this just a limitation developers have to live with?
|
Short answer: set the value of the exportselection attribute of all listbox widgets to False or zero.
From a pythonware overview of the listbox widget:
By default, the selection is exported
to the X selection mechanism. If you
have more than one listbox on the
screen, this really messes things up
for the poor user. If he selects
something in one listbox, and then
selects something in another, the
original selection is cleared. It is
usually a good idea to disable this
mechanism in such cases. In the
following example, three listboxes are
used in the same dialog:
b1 = Listbox(exportselection=0)
for item in families:
b1.insert(END, item)
b2 = Listbox(exportselection=0)
for item in fonts:
b2.insert(END, item)
b3 = Listbox(exportselection=0)
for item in styles:
b3.insert(END, item)
The definitive documentation for tk widgets is based on the Tcl language rather than python, but it is easy to translate to python. The exportselection attribute can be found on the standard options manual page.
|
How do you serialize a model instance in Django?
|
There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?
|
You can easily use a list to wrap the required object and that's all what django serializers need to correctly serialize it, eg.:
from django.core import serializers
# assuming obj is a model instance
serialized_obj = serializers.serialize('json', [ obj, ])
|
django-paypal setup
|
Has anyone setup django-paypal? Here is the link to it here?
I have "myproject" setup, and my folder sturecture looks like this:
myproject > paypal > (stdandard and pro folders)
to my settins.py file I added
INSTALLED_APPS = (
'myproject.paypal.standard',
'myproject.paypal.pro',
)
in my url's file for my account app I added:
urlpatterns += patterns('myproject.account.views',
(r'^payment-url/$', 'buy_my_item'),
)
and in my account view I added:
from myproject.paypal.pro.views import PayPalPro
from myproject.paypal.pro.forms import PaymentForm, ConfirmForm
def buy_my_item(request):
item = {'amt':"10.00", # amount to charge for item
'inv':"1111", # unique tracking variable paypal
'custom':"2222", # custom tracking variable for you
'cancelurl':"http://127.0.0.1:8000/", # Express checkout cancel url
'returnurl':"http://127.0.0.1:8000/"} # Express checkout return url
kw = {'item':'item', # what you're selling
'payment_template': 'pro/payment.html', # template to use for payment form
'confirm_template': ConfirmForm, # form class to use for Express checkout confirmation
'payment_form_cls': PaymentForm, # form class to use for payment
'success_url': '/success', # where to redirect after successful payment
}
ppp = PayPalPro(**kw)
return ppp(request)
--- EDIT ---------
Then, I added the pro and standard template folders to my projects template folder.
When I go to http://127.0.0.1:8000/account/payment-url/ and submit the form...
I get a ValueError : "dictionary update sequence element #0 has length 1; 2 is required"
Traceback:
File "...\accounts\views.py" in buy_my_item
655. return ppp(request)
File "...\paypal\pro\views.py" in __call__
115. return self.validate_payment_form()
File "...\paypal\pro\views.py" in validate_payment_form
133. success = form.process(self.request, self.item)
File "...\paypal\pro\forms.py" in process
params.update(item)
|
In your code...
'payment_form_cls': 'payment_form_cls', # form class to use for payment
This must be a Form object that's used for validation.
'payment_form_cls': MyValidationForm, # form class to use for payment
Edit
http://github.com/johnboxall/django-paypal/tree/master
Your request is supposed to include a notify-url, return-url and cancel-return. All three url's YOU provide to Paypal.
Paypal will send messages to these URL's.
Since Paypal will send messages to these URL's, YOU must put them in your urls.py. You must write view functions for these three urls'. These urls will have your paypal responses sent to them.
|
Make function definition in a python file order independent
|
I use Python CGI. I cannot call a function before it is defined.
In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.
Is there such a trick in Python as well?
example:
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def helper_function(hf_parameter):
....
def main():
do_something(my_value)
main()
David is right, my example is wrong.
What about:
<start of cgi-script>
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
print_something()
def helper_function(hf_parameter):
....
def main()
....
main()
Can I "forward declare" the functions at the top of the script?
|
All functions must be defined before any are used.
However, the functions can be defined in any order, as long as all are defined before any executable code uses a function.
You don't need "forward declaration" because all declarations are completely independent of each other. As long as all declarations come before all executable code.
Are you having a problem? If so, please post the code that doesn't work.
In your example, print_something() is out of place.
The rule: All functions must be defined before any code that does real work
Therefore, put all the statements that do work last.
|
PyQt4 Minimize to Tray
|
Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.
Has anybody done this? Any direction would be appreciated.
Using Python 2.5.4 and PyQt4 on Window XP Pro
|
It's pretty straightforward once you remember that there's no way to actually minimize to the system tray.
Instead, you fake it by doing this:
Catch the minimize event on your window
In the minimize event handler, create and show a QSystemTrayIcon
Also in the minimize event handler, call hide() or setVisible(false) on your window
Catch a click/double-click/menu item on your system tray icon
In your system tray icon event handler, call show() or setVisible(true) on your window, and optionally hide your tray icon.
|
How do I make text wrapping match current indentation level in vim?
|
Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.
For instance, if I set my settings so that the line:
print 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
is displayed when wrapped as:
print 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
then if I write a block of code like this:
def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
it wraps to something like this:
def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
I would prefer for it to be displayed as:
def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
Edit: after reading Don Werve's response, it seems that I am indeed looking for the breakindent option, but the option is still on the "Awaiting updated patches" list (see Vim TODO). So what I'd like to know is what is the easiest way to get vim working with breakindent? (I don't care what version of vim I have to use.)
|
I asked the same question on SuperUser, eventually found this question, found the patch, and updated the patch to work with Vim 7.2.148 from Fedora 11.
You can use yumdownloader --source vim to get the source RPM. Then add a Patch3312: line and a %patch3012 -p1 line to the spec file, and build the rpm.
|
How to use cherrypy as a web server for static files?
|
Is it any easy way to use CherryPy as an web server that will display .html files in some folder? All CherryPy introductory documentation states that content is dynamically generated:
import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
Is it any easy way to use index.html instead of HelloWorld.index() method?
|
This simple code will serve files on current directory.
import os
import cherrypy
PATH = os.path.abspath(os.path.dirname(__file__))
class Root(object): pass
cherrypy.tree.mount(Root(), '/', config={
'/': {
'tools.staticdir.on': True,
'tools.staticdir.dir': PATH,
'tools.staticdir.index': 'index.html',
},
})
cherrypy.quickstart()
|
Self updating py2exe/py2app application
|
I maintain a cross platform application, based on PyQt that runs on linux mac and windows.
The windows and mac versions are distributed using py2exe and py2app, which produces quite large bundles (~40 MB).
I would like to add an "auto update" functionality, based on patches to limit downloads size:
check for new versions on an http server
download the patches needed to update to the last version
apply the patches list and restart the application
I have some questions:
what is the preferred way to update a windows application since open files are locked and can't be overwritten ?
how do I prepare and apply the patches ? perhaps using bsdiff/pspatch ?
[update]
I made a simple class to make patches with bsdiff, which is very efficient as advertised on their site : a diff on two py2exe versions of my app (~75 MB uncompressed) produces a 44 kB patch ! Small enough for me, I will stick to this format.
The code is available in the 'update' package of pyflu, a small library of Python code.
|
I don't believe py2exe supports patched updates. However, if you do not bundle the entire package into a single EXE (py2exe website example - bottom of page), you can get away with smaller updates by just replacing certain files, like the EXE file, for example. This can reduce the size of your updates significantly.
You can write a separate updater app, which can be downloaded/ran from inside your application. This app may be different for every update, as the files that need to be updated may change.
Once the application launches the updater, it will need to close itself so the files can be overwritten. Once the updater is complete, you can have it reopen the application before closing itself.
|
Iterate over a python sequence in multiples of n?
|
How do I process the elements of a sequence in batches, idiomatically?
For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:
for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.
What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?
|
A generator function would be neat:
def batch_gen(data, batch_size):
for i in range(0, len(data), batch_size):
yield data[i:i+batch_size]
Example use:
a = "abcdef"
for i in batch_gen(a, 2): print i
prints:
ab
cd
ef
|
Long-running ssh commands in python paramiko module (and how to end them)
|
I want to run a tail -f logfile command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:
interface = paramiko.SSHClient()
#snip the connection setup portion
stdin, stdout, stderr = interface.exec_command("tail -f logfile")
#snip into threaded loop
print stdout.readline()
I'd like the command to run as long as necessary, but I have 2 problems:
How do I stop this cleanly? I thought of making a Channel and then using the shutdown() command on the channel when I'm through with it- but that seems messy. Is it possible to do something like sent Ctrl-C to the channel's stdin?
readline() blocks, and I could avoid threads if I had a non-blocking method of getting output- any thoughts?
|
Instead of calling exec_command on the client, get hold of the transport and generate your own channel. The channel can be used to execute a command, and you can use it in a select statement to find out when data can be read:
#!/usr/bin/env python
import paramiko
import select
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('host.example.com')
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command("tail -f /var/log/everything/current")
while True:
rl, wl, xl = select.select([channel],[],[],0.0)
if len(rl) > 0:
# Must be stdout
print channel.recv(1024)
The channel object can be read from and written to, connecting with stdout and stdin of the remote command. You can get at stderr by calling channel.makefile_stderr(...).
I've set the timeout to 0.0 seconds because a non-blocking solution was requested. Depending on your needs, you might want to block with a non-zero timeout.
|
Suppress the u'prefix indicating unicode' in python strings
|
Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?
|
You could use Python 3.0.. The default string type is unicode, so the u'' prefix is no longer required..
In short, no. You cannot turn this off.
The u comes from the unicode.__repr__ method, which is used to display stuff in REPL:
>>> print repr(unicode('a'))
u'a'
>>> unicode('a')
u'a'
If I'm not mistaken, you cannot override this without recompiling Python.
The simplest way around this is to simply print the string..
>>> print unicode('a')
a
If you use the unicode() builtin to construct all your strings, you could do something like..
>>> class unicode(unicode):
... def __repr__(self):
... return __builtins__.unicode.__repr__(self).lstrip("u")
...
>>> unicode('a')
a
..but don't do that, it's horrible
|
Is it ok to use dashes in Python files when trying to import them?
|
Basically when I have a python file like:
python-code.py
and use:
import (python-code)
the interpreter gives me syntax error.
Any ideas on how to fix it? Are dashes illegal in python file names?
|
You should check out PEP 8, the Style Guide for Python Code:
Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.
In other words: rename your file :)
|
Overriding 'to boolean' operator in python?
|
I'm using a class that is inherited from list as a data structure:
class CItem( list ) :
pass
oItem = CItem()
oItem.m_something = 10
oItem += [ 1, 2, 3 ]
All is perfect, but if I use my object of my class inside of an 'if', python evaluates it to False if underlying the list has no elements. Since my class is not just list, I really want it to evaluate False only if it's None, and evaluate to True otherwise:
a = None
if a :
print "this is not called, as expected"
a = CItem()
if a :
print "and this is not called too, since CItem is empty list. How to fix it?"
|
In 2.x: override __nonzero__(). In 3.x, override __bool__().
|
How to get the label of a choice in a Django forms ChoiceField?
|
I have a ChoiceField, now how do I get the "label" when I need it?
class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
form.cleaned_data["reason"] would only give me "feature" or "order" or so.
|
See the docs on Model.get_FOO_display(). So, should be something like :
ContactForm.get_reason_display()
In a template, use like this:
{{ OBJNAME.get_FIELDNAME_display }}
|
Trimming a string in Python
|
How do I remove leading and trailing whitespace from a string in Python?
For example:
" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
|
Just one space, or all such spaces? If the second, then strings already have a .strip() method:
>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> ' Hello '.strip() # ALL spaces at ends removed
'Hello'
If you need only to remove one space however, you could do it with:
def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s
>>> strip_one_space(" Hello ")
' Hello'
Also, note that str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip, i.e.:
>>> " Hello\n".strip(" ")
'Hello\n'
|
Python : How to convert markdown formatted text to text
|
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
|
This module will help do what you describe:
http://www.freewisdom.org/projects/python-markdown/Using_as_a_Module
Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text.
Your code might look something like this:
from BeautifulSoup import BeautifulSoup
from markdown import markdown
html = markdown(some_html_string)
text = ''.join(BeautifulSoup(html).findAll(text=True))
|
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
|
ft2build.h is located here:
C:\Program Files\GnuWin32\include
Initially, I made the same mistake as here:
http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director
but since then, I've corrected that particular error (I've added the above directory to the "include" list, rather than the "executables" list), but I still get an error. The complete output is this:
BUILDING MATPLOTLIB
matplotlib: 0.98.5.2
python: 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr
14 2009, 21:19:36) [MSC v.1500 32 bit (Intel)]
platform: win32
Windows version: (5, 1, 2600, 2, 'Service Pack 3')
REQUIRED DEPENDENCIES
numpy: 1.3.0
freetype2: found, but unknown version (no pkg-config)
* WARNING: Could not find 'freetype2' headers in any
* of '.', '.\freetype2'.
OPTIONAL BACKEND DEPENDENCIES
libpng: found, but unknown version (no pkg-config)
* Could not find 'libpng' headers in any of '.'
Tkinter: no
* No tk/win32 support for this python version yet
wxPython: 2.8.9.2
* WxAgg extension not required for wxPython >= 2.8
Gtk+: no
* Building for Gtk+ requires pygtk; you must be able
* to "import gtk" in your build/install environment
Mac OS X native: no
Qt: no
Qt4: no
Cairo: no
OPTIONAL DATE/TIMEZONE DEPENDENCIES
datetime: present, version unknown
dateutil: matplotlib will provide
pytz: matplotlib will provide
OPTIONAL USETEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
[Edit setup.cfg to suppress the above messages]
============================================================================
pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends', 'matplotlib.projections', 'mpl_to
olkits', 'matplotlib.numerix', 'matplotlib.numerix.mlab', 'matplotlib.numerix.ma
', 'matplotlib.numerix.npyma', 'matplotlib.numerix.linear_algebra', 'matplotlib.
numerix.random_array', 'matplotlib.numerix.fft', 'matplotlib.delaunay', 'pytz',
'dateutil', 'dateutil/zoneinfo']
running build
running build_py
copying lib\matplotlib\mpl-data\matplotlibrc -> build\lib.win32-2.6\matplotlib\m
pl-data
copying lib\matplotlib\mpl-data\matplotlib.conf -> build\lib.win32-2.6\matplotli
b\mpl-data
running build_ext
building 'matplotlib.ft2font' extension
C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W
3 /GS- /DNDEBUG -IC:\Python26\lib\site-packages\numpy\core\include -I. -IC:\Pyth
on26\lib\site-packages\numpy\core\include\freetype2 -I.\freetype2 -IC:\Python26\
include -IC:\Python26\include\Stackless -IC:\Python26\PC /Tpsrc/ft2font.cpp /Fob
uild\temp.win32-2.6\Release\src/ft2font.obj
ft2font.cpp
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: C++ exception handler used, but unwind semantics are not enabled. Specify
/EHsc
c:\python26\lib\site-packages\matplotlib-0.98.5.2\src\ft2font.h(13) : fatal erro
r C1083: Cannot open include file: 'ft2build.h': No such file or directory
error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa
iled with exit status 2
I should mention that this is Python 2.6
|
This error comes about when building matplotlib on Ubuntu 10.10 also. The solution is to do:
sudo apt-get install python-dev libfreetype6-dev
|
python, "a in b" keyword, how about multiple a's?
|
My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:
if "a" in "abrakadabra" :
print "it is definitely here"
But is it possible to test if more than one item is in the list (any one)?
Currently, I'm using the syntax below, but it is kinda long:
if "// @in " in sTxt or "// @out " in sTxt or "// @ret " in sTxt or <10 more>
print "found."
Of course regexes can help, but using regexes will take lots of verbose of code and will
not be as clear as "a in b". Are there any other Pythonic ways?
|
alternatives = ("// @in ", "// @out ", "// @ret ")
if any(a in sTxT for a in alternatives):
print "found"
if all(a in sTxT for a in alternatives):
print "found all"
any() and all() takes an iterable and checks if any/all of them evaluate to a true value. Combine that with a generator expressions, and you can check multiple items.
|
Determine if a function is available in a Python module
|
I am working on some Python socket code that's using the socket.fromfd() function.
However, this method is not available on all platforms, so I am writing some fallback code in the case that the method is not defined.
What's the best way to determine if a method is defined at runtime? Is the following sufficient or is there a better idiom?
if 'fromfd' in dir(socket):
sock = socket.fromfd(...)
else:
sock = socket.socket(...)
I'm slightly concerned that the documentation for dir() seems to discourage its use. Would getattr() be a better choice, as in:
if getattr(socket, 'fromfd', None) is not None:
sock = socket.fromfd(...)
else:
sock = socket.socket(...)
Thoughts?
EDIT As Paolo pointed out, this question is nearly a duplicate of a question about determining attribute presence. However, since the terminology used is disjoint (lk's "object has an attribute" vs my "module has a function") it may be helpful to preserve this question for searchability unless the two can be combined.
|
hasattr() is the best choice. Go with that. :)
if hasattr(socket, 'fromfd'):
pass
else:
pass
EDIT: Actually, according to the docs all hasattr is doing is calling getattr and catching the exception. So if you want to cut out the middle man you should go with marcog's answer.
EDIT: I also just realized this question is actually a duplicate. One of the answers there discusses the merits of the two options you have: catching the exception ("easier to ask for forgiveness than permission") or simply checking before hand ("look before you leap"). Honestly, I am more of the latter, but it seems like the Python community leans towards the former school of thought.
|
Python: How do I get time from a datetime.timedelta object?
|
A mysql database table has a column whose datatype is time ( http://dev.mysql.com/doc/refman/5.0/en/time.html ). When the table data is accessed, Python returns the value of this column as a datetime.timedelta object. How do I extract the time out of this? (I didn't really understand what timedelta is for from the python manuals).
E.g. The column in the table contains the value "18:00:00"
Python-MySQLdb returns this as datetime.timedelta(0, 64800)
Please ignore what is below (it does return different value) -
Added: Irrespective of the time value in the table, python-MySQLdb seems to only return datetime.timedelta(0, 64800).
Note: I use Python 2.4
|
It's strange that Python returns the value as a datetime.timedelta. It probably should return a datetime.time. Anyway, it looks like it's returning the elapsed time since midnight (assuming the column in the table is 6:00 PM). In order to convert to a datetime.time, you can do the following::
value = datetime.timedelta(0, 64800)
(datetime.datetime.min + value).time()
datetime.datetime.min and datetime.time() are, of course, documented as part of the datetime module if you want more information.
A datetime.timedelta is, by the way, a representation of the difference between two datetime.datetime values. So if you subtract one datetime.datetime from another, you will get a datetime.timedelta. And if you add a datetime.datetime with a datetime.timedelta, you'll get a datetime.datetime. That's how the code above works.
|
Dictionary to lowercase in Python
|
I wish to do this but for a dictionary:
"My string".lower()
Is there a built in function or should I use a loop?
|
You will need to use either a loop or a list/generator comprehension. If you want to lowercase all the keys and values, you can do this::
dict((k.lower(), v.lower()) for k,v in {'My Key':'My Value'}.iteritems())
If you want to lowercase just the keys, you can do this::
dict((k.lower(), v) for k,v in {'My Key':'My Value'}.iteritems())
Generator expressions (used above) are often useful in building dictionaries; I use them all the time. All the expressivity of a loop comprehension with none of the memory overhead.
|
A list of string replacements in Python
|
Is there a far shorter way to write the following code?
my_string = my_string.replace('A', '1')
my_string = my_string.replace('B', '2')
my_string = my_string.replace('C', '3')
my_string = my_string.replace('D', '4')
my_string = my_string.replace('E', '5')
Note that I don't need those exact values replaced; I'm simply looking for a way to turn 5+ lines into fewer than 5
|
Looks like a good opportunity to use a loop:
mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'}
for k, v in mapping.iteritems():
my_string = my_string.replace(k, v)
A faster approach if you don't mind the parentheses would be:
mapping = [ ('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5') ]
for k, v in mapping:
my_string = my_string.replace(k, v)
|
Python Macros: Use Cases?
|
If Python had a macro facility similar to Lisp/Scheme (something like MetaPython), how would you use it?
If you are a Lisp/Scheme programmer, what sorts of things do you use macros for (other than things that have a clear syntactic parallel in Python such as a while loop)?
|
I believe that macros run counter to Python's culture. Macros in Lisp allow the big ball of mud approach; you get to redefine the language to become more suited to your problem domain. Conversely Pythonic code uses the most natural built in feature of Python to solve a problem, instead of solving it in a way that would be more natural in a different language.
Macros are inherently unpythonic.
|
How to hide console window in python?
|
I am writing an IRC bot in Python.
I wish to make stand-alone binaries for Linux and Windows of it. And mainly I wish that when the bot initiates, the console window should hide and the user should not be able to see the window.
What can I do for that?
|
Simply save it with a .pyw extension. This will prevent the console window from opening.
On Windows systems, there is no notion of an âexecutable modeâ. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.
Explanation at the bottom of section 2.2.2
|
SQLite Performance Benchmark -- why is :memory: so slow...only 1.5X as fast as disk?
|
Why is :memory: in sqlite so slow?
I've been trying to see if there are any performance improvements gained by using in-memory sqlite vs. disk based sqlite. Basically I'd like to trade startup time and memory to get extremely rapid queries which do not hit disk during the course of the application.
However, the following benchmark gives me only a factor of 1.5X in improved speed. Here, I'm generating 1M rows of random data and loading it into both a disk and memory based version of the same table. I then run random queries on both dbs, returning sets of size approx 300k. I expected the memory based version to be considerably faster, but as mentioned I'm only getting 1.5X speedups.
I experimented with several other sizes of dbs and query sets; the advantage of :memory: does seem to go up as the number of rows in the db increases. I'm not sure why the advantage is so small, though I had a few hypotheses:
the table used isn't big enough (in rows) to make :memory: a huge winner
more joins/tables would make the :memory: advantage more apparent
there is some kind of caching going on at the connection or OS level such that the previous results are accessible somehow, corrupting the benchmark
there is some kind of hidden disk access going on that I'm not seeing (I haven't tried lsof yet, but I did turn off the PRAGMAs for journaling)
Am I doing something wrong here? Any thoughts on why :memory: isn't producing nearly instant lookups? Here's the benchmark:
==> sqlite_memory_vs_disk_benchmark.py <==
#!/usr/bin/env python
"""Attempt to see whether :memory: offers significant performance benefits.
"""
import os
import time
import sqlite3
import numpy as np
def load_mat(conn,mat):
c = conn.cursor()
#Try to avoid hitting disk, trading safety for speed.
#http://stackoverflow.com/questions/304393
c.execute('PRAGMA temp_store=MEMORY;')
c.execute('PRAGMA journal_mode=MEMORY;')
# Make a demo table
c.execute('create table if not exists demo (id1 int, id2 int, val real);')
c.execute('create index id1_index on demo (id1);')
c.execute('create index id2_index on demo (id2);')
for row in mat:
c.execute('insert into demo values(?,?,?);', (row[0],row[1],row[2]))
conn.commit()
def querytime(conn,query):
start = time.time()
foo = conn.execute(query).fetchall()
diff = time.time() - start
return diff
#1) Build some fake data with 3 columns: int, int, float
nn = 1000000 #numrows
cmax = 700 #num uniques in 1st col
gmax = 5000 #num uniques in 2nd col
mat = np.zeros((nn,3),dtype='object')
mat[:,0] = np.random.randint(0,cmax,nn)
mat[:,1] = np.random.randint(0,gmax,nn)
mat[:,2] = np.random.uniform(0,1,nn)
#2) Load it into both dbs & build indices
try: os.unlink('foo.sqlite')
except OSError: pass
conn_mem = sqlite3.connect(":memory:")
conn_disk = sqlite3.connect('foo.sqlite')
load_mat(conn_mem,mat)
load_mat(conn_disk,mat)
del mat
#3) Execute a series of random queries and see how long it takes each of these
numqs = 10
numqrows = 300000 #max number of ids of each kind
results = np.zeros((numqs,3))
for qq in range(numqs):
qsize = np.random.randint(1,numqrows,1)
id1a = np.sort(np.random.permutation(np.arange(cmax))[0:qsize]) #ensure uniqueness of ids queried
id2a = np.sort(np.random.permutation(np.arange(gmax))[0:qsize])
id1s = ','.join([str(xx) for xx in id1a])
id2s = ','.join([str(xx) for xx in id2a])
query = 'select * from demo where id1 in (%s) AND id2 in (%s);' % (id1s,id2s)
results[qq,0] = round(querytime(conn_disk,query),4)
results[qq,1] = round(querytime(conn_mem,query),4)
results[qq,2] = int(qsize)
#4) Now look at the results
print " disk | memory | qsize"
print "-----------------------"
for row in results:
print "%.4f | %.4f | %d" % (row[0],row[1],row[2])
Here's the results. Note that disk takes about 1.5X as long as memory for a fairly wide range of query sizes.
[ramanujan:~]$python -OO sqlite_memory_vs_disk_clean.py
disk | memory | qsize
-----------------------
9.0332 | 6.8100 | 12630
9.0905 | 6.6953 | 5894
9.0078 | 6.8384 | 17798
9.1179 | 6.7673 | 60850
9.0629 | 6.8355 | 94854
8.9688 | 6.8093 | 17940
9.0785 | 6.6993 | 58003
9.0309 | 6.8257 | 85663
9.1423 | 6.7411 | 66047
9.1814 | 6.9794 | 11345
Shouldn't RAM be almost instant relative to disk? What's going wrong here?
Edit
Some good suggestions here.
I guess the main takehome point for me is that **there's probably no way to make :memory: absolutely faster, but there is a way to make disk access relatively slower. **
In other words, the benchmark is adequately measuring the realistic performance of memory, but not the realistic performance of disk (e.g. because the cache_size pragma is too big or because I'm not doing writes). I'll mess around with those parameters and post my findings when I get a chance.
That said, if there is anyone who thinks I can squeeze some more speed out of the in-memory db (other than by jacking up the cache_size and default_cache_size, which I will do), I'm all ears...
|
It has to do with the fact that SQLite has a page cache. According to the Documentation, the default page cache is 2000 1K pages or about 2Mb. Since this is about 75% to 90% of your data, it isn't surprising that the two number are very similar. My guess is that in addition to the SQLite page cache, the rest of the data is still in the OS disk cache. If you got SQLite to flush the page cache (and the disk cache) you would see some really significant differences.
|
How's Python Multiprocessing Implemented on Windows?
|
Given the absence of a Windows fork() call, how's the multiprocessing package in Python 2.6 implemented under Windows? On top of Win32 threads or some sort of fake fork or just compatibility on top of the existing multithreading?
|
It's done using a subprocess call to sys.executable (i.e. start a new Python process) followed by serializing all of the globals, and sending those over the pipe. A poor man's cloning of the current process. This is the cause of the extra restrictions found when using multiprocessing on Windows plaform.
You may also be interested in viewing Jesse Noller's talk from PyCon about multiprocessing where he discusses its use.
|
Using PIL to make all white pixels transparent?
|
I'm trying to make all white pixels transparent using the Python Image Library. (I'm a C hacker trying to learn python so be gentle)
I've got the conversion working (at least the pixel values look correct) but I can't figure out how to convert the list into a buffer to re-create the image. Here's the code
img = Image.open('img.png')
imga = img.convert("RGBA")
datas = imga.getdata()
newData = list()
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append([255, 255, 255, 0])
else:
newData.append(item)
imgb = Image.frombuffer("RGBA", imga.size, newData, "raw", "RGBA", 0, 1)
imgb.save("img2.png", "PNG")
|
You need to make the following changes:
append a tuple (255, 255, 255, 0) and not a list [255, 255, 255, 0]
use img.putdata(newData)
This is the working code:
from PIL import Image
img = Image.open('img.png')
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
img.save("img2.png", "PNG")
|
Python timedelta in years
|
I need to check if some number of years have been since some date. Currently I've got timedelta from datetime module and I don't know how to convert it to years.
|
You need more than a timedelta to tell how many years have passed; you also need to know the beginning (or ending) date. (It's a leap year thing.)
Your best bet is to use the dateutil.relativedelta object, but that's a 3rd party module. If you want to know the datetime that was n years from some date (defaulting to right now), you can do the following::
from dateutil.relativedelta import relativedelta
def yearsago(years, from_date=None):
if from_date is None:
from_date = datetime.now()
return from_date - relativedelta(years=years)
If you'd rather stick with the standard library, the answer is a little more complex::
from datetime import datetime
def yearsago(years, from_date=None):
if from_date is None:
from_date = datetime.now()
try:
return from_date.replace(year=from_date.year - years)
except ValueError:
# Must be 2/29!
assert from_date.month == 2 and from_date.day == 29 # can be removed
return from_date.replace(month=2, day=28,
year=from_date.year-years)
If it's 2/29, and 18 years ago there was no 2/29, this function will return 2/28. If you'd rather return 3/1, just change the last return statement to read::
return from_date.replace(month=3, day=1,
year=from_date.year-years)
Your question originally said you wanted to know how many years it's been since some date. Assuming you want an integer number of years, you can guess based on 365.25 days per year and then check using either of the yearsago functions defined above::
def num_years(begin, end=None):
if end is None:
end = datetime.now()
num_years = int((end - begin).days / 365.25)
if begin > yearsago(num_years, end):
return num_years - 1
else:
return num_years
|
reverse a string in Python
|
I was looking for a way to print a string backwards, and after a quick search on google, I found this method:
Suppose 'a' is a string variable. This will return the 'a' string backwards:
a[::-1]
Can anyone explain how that works?
|
Sure, the [::] is the extended slice operator. It allows you to take substrings. Basically, it works by specifying which elements you want as [begin:end:step], and it works for all sequences. Two neat things about it:
You can omit one or more of the elements and it does "the right thing"
Negative numbers for begin, end, and step have meaning
For begin and end, if you give a negative number, it means to count from the end of the sequence. For instance, if I have a list:
l = [1,2,3]
Then l[-1] is 3, l[-2] is 2, and l[-3] is 1.
For the step argument, a negative number means to work backwards through the sequence. So for a list::
l = [1,2,3,4,5,6,7,8,9,10]
You could write l[::-1] which basically means to use a step size of -1 while reading through the list. Python will "do the right thing" when filling in the start and stop so it iterates through the list backwards and gives you [10,9,8,7,6,5,4,3,2,1].
I've given the examples with lists, but strings are just another sequence and work the same way. So a[::-1] means to build a string by joining the characters you get by walking backwards through the string.
|
Python speed testing - Time Difference - milliseconds
|
What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.
So far I have this code:
from datetime import datetime
tstart = datetime.now()
print t1
# code to speed test
tend = datetime.now()
print t2
# what am I missing?
# I'd like to print the time diff here
|
datetime.timedelta is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a
>>> c
datetime.timedelta(0, 4, 316543)
>>> c.days
0
>>> c.seconds
4
>>> c.microseconds
316543
Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().
You can do all sorts of maths with datetime.timedelta, eg:
>>> c / 10
datetime.timedelta(0, 0, 431654)
It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command.
|
Python non-greedy regexes
|
How do I make a python regex like "(.*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?
I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
|
You seek the all-powerful '*?'
http://docs.python.org/2/howto/regex.html#greedy-versus-non-greedy
|
Riddle: The Square Puzzle
|
Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle:
There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse rules" and reach number 100 (or 99 if you're a programmer and start with 0 instead :)
The rules for traversing are:
1. Two spaces hop along the vertical and horizontal axis
2. One space hop along the diagonals
3. You can visit each square only once
To visualise better, here is a valid example traverse (up to the 8th step):
Manually, I have been working on this puzzle out of boredom. For years, I have tried to solve it by hand from time to time, but I have never gone beyond 96. Sounds easy? Try yourself and see for yourself :)
Thus, in order to solve the problem, I have developed a short (around 100 lines of code) program in Python. I am a beginner in this language I wanted to see what I can do.
The program simply applies exhaustive try & error solving technique. In other words: brute force depth first search.
My question arises from here on: The program, unfortunately cannot solve the problem because the state space is so big that search never ends withouh ever finding a solution. It can go up to number 98 (and prints that) without much difficulty, nonetheless not a complete solution.
The program also prints out the length of the search tree it has covered so far. In a couple of minutes, the traverse list from, say, 65th element is covered till the end, for just one single path. This number decreases in exponentially increasing time periods. I have run the code for quite some time and could not get beyond 50 barrier and now I am convinced.
It seems that this simple approach will not be enough unless I run it for ever. So, how can I improve my code to be faster and more efficient so that it comes up with solutions?
Basically, I am looking forward to see ideas on how to:
Capture and exploit domain knowledge specific to this problem
Apply programming techniques/tricks to overcome exhaustion
..and finally realize into a substantial solution.
Thanks in advance.
Revision
Thanks to Dave Webb for relating the problem to domain it belongs:
This is very similar to the Knight's
Tour problem which relates moving a
knight around a chess board without
revisiting the same square. Basically
it's the same problem but with
different "Traverse Rules".
|
This is very similar to the Knight's Tour problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".
The key optimisation I remember from tackling the Knights Tour recursively is take your next moves in increasing order of the number of available moves on the destination square. This encourages the search to try and move densely in one area and filling it rather than zooming all over the board and leaving little island squares that can never be visited. (This is Warnsdorff's algorithm.)
Also make sure you have considered symmetry where you can. For example, at the simplest level the x and y of your starting square only need to go up to 5 since (10,10) is the same as (1,1) with the board rotated.
|
What is the most Pythonic way to provide a fall-back value in an assignment?
|
In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:
my $x = undef;
my $y = 2;
my $a = $x || $y;
After this,
$a == 2
Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...
if x is not None
a = x
else
a = y
... be the most Pythonic way to achieve this?
EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.
|
Since 2.5:
If you want to fall back only on None:
a = x if x is not None else y
If you want to fall back also on empty string, false, 0 etc.:
a = x if x else y
or
a = x or y
As for undefined (as never defined, a.k.a. not bound):
try:
a = x
except NameError:
a = y
or a bit more hackish (I'd not really recommend that, but it's short):
a = vars().get('x',y)
|
Common ways to connect to odbc from python on windows?
|
What library should I use to connect to odbc from python on windows? Is there a good alternative for pywin32 when it comes to odbc?
I'm looking for something well-documented, robust, actively maintained, etc. pyodbc looks good -- are there any others?
|
You already suggested pyodbc, and I am going to agree with you.
It has given me the least amount of issues in my experience; I've used pymssql and adodbapi, and when those threw exceptions/created issues, I swapped out the code and replaced it with pyodbc and it either fixed the problem, or gave better error messages so I could debug faster.
It's worth mentioning that I primarily use it to connect to MSSQL Server DBs.
|
Parse a .py file, read the AST, modify it, then write back the modified source code
|
I want to programmatically edit python source code. Basically I want to read a .py file, generate the AST, and then write back the modified python source code (i.e. another .py file).
There are ways to parse/compile python source code using standard python modules, such as ast or compiler. However, I don't think any of them support ways to modify the source code (e.g. delete this function declaration) and then write back the modifying python source code.
UPDATE: The reason I want to do this is I'd like to write a Mutation testing library for python, mostly by deleting statements / expressions, rerunning tests and seeing what breaks.
|
Pythoscope does this to the test cases it automatically generates as does the 2to3 tool for python 2.6 (it converts python 2.x source into python 3.x source).
Both these tools uses the lib2to3 library which is a implementation of the python parser/compiler machinery that can preserve comments in source when it's round tripped from source -> AST -> source.
The rope project may meet your needs if you want to do more refactoring like transforms.
The ast module is your other option, and there's an older example of how to "unparse" syntax trees back into code (using the parser module). But the ast module is more useful when doing an AST transform on code that is then transformed into a code object.
The redbaron project also may be a good fit (ht Xavier Combelle)
|
How do I use AND in a Django filter?
|
How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.
For example the following SQL query does exactly that when I run it on mysql database:
select * from myapp_question
where ((question like '%software%') and (question like '%java%'))
How do you accomplish this in Django using filters?
|
For thoroughness sake, let's just mention the Q object method:
from django.db.models import Q
criterion1 = Q(question__contains="software")
criterion2 = Q(question__contains="java")
q = Question.objects.filter(criterion1 & criterion2)
Note the other answers here are simpler and better adapted for your use case, but if anyone with a similar but slightly more complex problem (such as needing "not" or "or") sees this, it's good to have the reference right here.
|
What does the Python Ellipsis object do?
|
While idly surfing the namespace I noticed an odd looking object called "Ellipsis", it does not seem to be or do anything special, but it's a globally available builtin.
After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else.
Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?
D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
|
This came up in another question recently. I'll elaborate on my answer from there:
Ellipsis is an object that can appear in slice notation. For example:
myList[1:2, ..., 0]
Its interpretation is purely up to whatever implements the __getitem__ function and sees Ellipsis objects there, but its main (and intended) use is in the numeric python extension, which adds a multidimensional array type. Since there are more than one dimensions, slicing becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimensions as well. E.g., given a 4x4 array, the top left area would be defined by the slice [:2,:2]:
>>> a
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
>>> a[:2,:2] # top left
array([[1, 2],
[5, 6]])
Extending this further, Ellipsis is used here to indicate a placeholder for the rest of the array dimensions not specified. Think of it as indicating the full slice [:] for all the dimensions in the gap it is placed, so for a 3d array, a[...,0] is the same as a[:,:,0] and for 4d, a[:,:,:,0], similarly, a[0,...,0] is a[0,:,:,0] (with however many colons in the middle make up the full number of dimensions in the array).
Interestingly, in python3, the Ellipsis literal (...) is usable outside the slice syntax, so you can actually write:
>>> ...
Ellipsis
Other than the various numeric types, no, I don't think it's used. As far as I'm aware, it was added purely for numpy use and has no core support other than providing the object and corresponding syntax. The object being there didn't require this, but the literal "..." support for slices did.
|
Django payment proccessing
|
Can anyone suggest any good payment processing libraries for python/django?
|
The most developed Django solution is Satchmo with support for Authorize.Net, TrustCommerce, CyberSource, PayPal, Google Checkout, and Protx.
The new kid on the Django block is django-lfs which looks like only support for PayPal at the moment, and even that may not be complete.
For general Python the main player is getpaid
|
Why are 0d arrays in Numpy not considered scalar?
|
Surely a 0d array is scalar, but Numpy does not seem to think so... am I missing something or am I just misunderstanding the concept?
>>> foo = numpy.array(1.11111111111, numpy.float64)
>>> numpy.ndim(foo)
0
>>> numpy.isscalar(foo)
False
>>> foo.item()
1.11111111111
|
One should not think too hard about it. It's ultimately better for the mental health and longevity of the individual.
The curious situation with Numpy scalar-types was bore out of the fact that there is no graceful and consistent way to degrade the 1x1 matrix to scalar types. Even though mathematically they are the same thing, they are handled by very different code.
If you've been doing any amount of scientific code, ultimately you'd want things like max(a) to work on matrices of all sizes, even scalars. Mathematically, this is a perfectly sensible thing to expect. However for programmers this means that whatever presents scalars in Numpy should have the .shape and .ndim attirbute, so at least the ufuncs don't have to do explicit type checking on its input for the 21 possible scalar types in Numpy.
On the other hand, they should also work with existing Python libraries that does do explicit type-checks on scalar type. This is a dilemma, since a Numpy ndarray have to individually change its type when they've been reduced to a scalar, and there is no way of knowing whether that has occurred without it having do checks on all access. Actually going that route would probably make bit ridiculously slow to work with by scalar type standards.
The Numpy developer's solution is to inherit from both ndarray and Python scalars for its own scalary type, so that all scalars also have .shape, .ndim, .T, etc etc. The 1x1 matrix will still be there, but its use will be discouraged if you know you'll be dealing with a scalar. While this should work fine in theory, occasionally you could still see some places where they missed with the paint roller, and the ugly innards are exposed for all to see:
>>> from numpy import *
>>> a = array(1)
>>> b = int_(1)
>>> a.ndim
0
>>> b.ndim
0
>>> a[...]
array(1)
>>> a[()]
1
>>> b[...]
array(1)
>>> b[()]
1
There's really no reason why a[...] and a[()] should return different things, but it does. There are proposals in place to change this, but looks like they forgot to finish the job for 1x1 arrays.
A potentially bigger, and possibly non-resolvable issue, is the fact that Numpy scalars are immutable. Therefore "spraying" a scalar into a ndarray, mathematically the adjoint operation of collapsing an array into a scalar, is a PITA to implement. You can't actually grow a Numpy scalar, it cannot by definition be cast into an ndarray, even though newaxis mysteriously works on it:
>>> b[0,1,2,3] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'numpy.int32' object does not support item assignment
>>> b[newaxis]
array([1])
In Matlab, growing the size of a scalar is a perfectly acceptable and brainless operation. In Numpy you have to stick jarring a = array(a) everywhere you think you'd have the possibility of starting with a scalar and ending up with an array. I understand why Numpy has to be this way to play nice with Python, but that doesn't change the fact that many new switchers are deeply confused about this. Some have explicit memory of struggling with this behaviour and eventually persevering, while others who are too far gone are generally left with some deep shapeless mental scar that frequently haunts their most innocent dreams. It's an ugly situation for all.
|
Plot logarithmic axes with matplotlib in python
|
I want to plot a graph with one logarithmic axis using matplotlib.
I've been reading the docs, but can't figure out the syntax. I know that it's probably something simple like 'scale=linear' in the plot arguments, but I can't seem to get it right
Sample program:
from pylab import *
import matplotlib.pyplot as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)
line, = ax.plot(a, color='blue', lw=2)
show()
|
You can use the Axes.set_yscale method. That allows you to change the scale after the Axes object is created. That would also allow you to build a control to let the user pick the scale if you needed to.
The relevant line to add is:
ax.set_yscale('log')
You can use 'linear' to switch back to a linear scale. Here's what your code would look like:
from pylab import *
import matplotlib.pyplot as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)
line, = ax.plot(a, color='blue', lw=2)
ax.set_yscale('log')
show()
|
Python difflib: highlighting differences inline?
|
When comparing similar lines, I want to highlight the differences on the same line:
a) lorem ipsum dolor sit amet
b) lorem foo ipsum dolor amet
lorem <ins>foo</ins> ipsum dolor <del>sit</del> amet
While difflib.HtmlDiff appears to do this sort of inline highlighting, it produces very verbose markup.
Unfortunately, I have not been able to find another class/method which does not operate on a line-by-line basis.
Am I missing anything?
Any pointers would be appreciated!
|
For your simple example:
import difflib
def show_diff(seqm):
"""Unify operations between two compared strings
seqm is a difflib.SequenceMatcher instance whose a & b are strings"""
output= []
for opcode, a0, a1, b0, b1 in seqm.get_opcodes():
if opcode == 'equal':
output.append(seqm.a[a0:a1])
elif opcode == 'insert':
output.append("<ins>" + seqm.b[b0:b1] + "</ins>")
elif opcode == 'delete':
output.append("<del>" + seqm.a[a0:a1] + "</del>")
elif opcode == 'replace':
raise NotImplementedError, "what to do with 'replace' opcode?"
else:
raise RuntimeError, "unexpected opcode"
return ''.join(output)
>>> sm= difflib.SequenceMatcher(None, "lorem ipsum dolor sit amet", "lorem foo ipsum dolor amet")
>>> show_diff(sm)
'lorem<ins> foo</ins> ipsum dolor <del>sit </del>amet'
This works with strings. You should decide what to do with "replace" opcodes.
|
Explain Python entry points?
|
I've read the documentation on egg entry points in Pylons and on the Peak pages, and I still don't really understand. Could someone explain them to me, or point me at an article or book that does?
|
EntryPoints provide a persistent, filesystem-based object name registration and name-based direct object import mechanism (implemented by the setuptools package).
They associate names of Python objects with free-form identifiers. So any other code using the same Python installation and knowing the identifier can access an object with the associated name, no matter where the object is defined. The associated names can be any names existing in a Python module; for example name of a class, function or variable. The entry point mechanism does not care what the name refers to, as long as it is importable.
As an example, let's use (the name of) a function, and an imaginary python module with a fully-qualified name 'myns.mypkg.mymodule':
def the_function():
"function whose name is 'the_function', in 'mymodule' module"
print "hello from the_function"
Entry points are registered via an entry points declaration in setup.py. To register the_function under entrypoint called 'my_ep_func':
entry_points = {
'my_ep_group_id': [
'my_ep_func = myns.mypkg.mymodule:the_function'
]
},
As the example shows, entry points are grouped; there's corresponding API to look up all entry points belonging to a group (example below).
Upon a package installation (ie. running 'python setup.py install'), the above declaration is parsed by setuptools. It then writes the parsed information in special file. After that, the pkg_resources API (part of setuptools) can be used to look up the entry point and access the object(s) with the associated name(s):
import pkg_resources
named_objects = {}
for ep in pkg_resources.iter_entry_points(group='my_ep_group_id'):
named_objects.update({ep.name: ep.load()})
Here, setuptools read the entry point information that was written in special files. It found the entry point, imported the module (myns.mypkg.mymodule), and retrieved the_function defined there, upon call to pkg_resources.load().
Assuming there were no other entry point registrations for the same group id, calling the_function would then be simple:
>>> named_objects['my_ep_func']()
hello from the_function
Thus, while perhaps a bit difficult to grasp at first, the entry point mechanism is actually quite simple to use. It provides an useful tool for pluggable Python software development.
|
Python Time Seconds to h:m:s
|
I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python?
|
or you can do
>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
|
Python MySQL Parameterized Queries
|
I am having a hard time using the MySQLdb module to insert information into my database. I need to insert 6 variables into the table.
cursor.execute ("""
INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
VALUES
(var1, var2, var3, var4, var5, var6)
""")
Can someone help me with the syntax here?
|
Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. The difference might seem trivial, but in reality it's huge.
Incorrect (with security issues)
c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2))
Correct (with escaping)
c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))
It adds to the confusion that the modifiers used to bind parameters in a SQL statement varies between different DB API implementations and that the mysql client library uses printf style syntax instead of the more commonly accepted '?' marker (used by eg. python-sqlite).
|
os.path.exists() for files in your Path?
|
I commonly use os.path.exists() to check if a file is there before doing anything with it.
I've run across a situation where I'm calling a executable that's in the configured env path, so it can be called without specifying the abspath.
Is there something that can be done to check if the file exists before calling it?
(I may fall back on try/except, but first I'm looking for a replacement for os.path.exists())
btw - I'm doing this on windows.
|
You could get the PATH environment variable, and try "exists()" for the .exe in each dir in the path. But that could perform horribly.
example for finding notepad.exe:
import os
for p in os.environ["PATH"].split(os.pathsep):
print os.path.exists(os.path.join(p, 'notepad.exe'))
more clever example:
if not any([os.path.exists(os.path.join(p, executable) for p in os.environ["PATH"].split(os.pathsep)]):
print "can't find %s" % executable
Is there a specific reason you want to avoid exception? (besides dogma?)
|
Multiple simultaneous network connections - Telnet server, Python
|
I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.
My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one.
This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):
import socket, os
class Server:
def __init__(self):
self.host, self.port = 'localhost', 50000
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((self.host, self.port))
def send(self, msg):
if type(msg) == str: self.conn.send(msg + end)
elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end)
def recv(self):
self.conn.recv(4096).strip()
def exit(self):
self.send('Disconnecting you...'); self.conn.close(); self.run()
# closing a connection, opening a new one
# main runtime
def run(self):
self.socket.listen(1)
self.conn, self.addr = self.socket.accept()
# there would be more activity here
# i.e.: sending things to the connection we just made
S = Server()
S.run()
Thanks for your help.
|
Implemented in twisted:
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
class SendContent(Protocol):
def connectionMade(self):
self.transport.write(self.factory.text)
self.transport.loseConnection()
class SendContentFactory(Factory):
protocol = SendContent
def __init__(self, text=None):
if text is None:
text = """Hello, how are you my friend? Feeling fine? Good!"""
self.text = text
reactor.listenTCP(50000, SendContentFactory())
reactor.run()
Testing:
$ telnet localhost 50000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello, how are you my friend? Feeling fine? Good!
Connection closed by foreign host.
Seriously, when it comes to asynchronous network, twisted is the way to go. It handles multiple connections in a single-thread single-process approach.
|
Efficient arbitrary-sized integer packing in Python
|
The struct.pack() function allows converting integers of up to 64 bit to byte strings. What's the most efficient way to pack an even larger integer? I'd rather not add a dependency on non-standard modules like PyCrypto (which provides num_to_bytes()).
|
Do you mean something like this:
def num_to_bytes(num):
bytes = []
num = abs(num) # Because I am unsure about negatives...
while num > 0:
bytes.append(chr(num % 256))
num >>= 8
return ''.join(reversed(bytes))
def bytes_to_num(bytes):
num = 0
for byte in bytes:
num <<= 8
num += ord(byte)
return num
for n in (1, 16, 256, 257, 1234567890987654321):
print n,
print num_to_bytes(n).encode('hex'),
print bytes_to_num(num_to_bytes(n))
Which returns:
1 01 1
16 10 16
256 0100 256
257 0101 257
1234567890987654321 112210f4b16c1cb1 1234567890987654321
I'm just not sure what to do about negatives... I'm not that familiar with bit twidling.
EDIT: Another solution (which runs about 30% faster by my tests):
def num_to_bytes(num):
num = hex(num)[2:].rstrip('L')
if len(num) % 2:
return ('0%s' % num).decode('hex')
return num.decode('hex')
def bytes_to_num(bytes):
return int(bytes.encode('hex'), 16)
|
smtplib and gmail - python script problems
|
Here's my script:
#!/usr/bin/python
import smtplib
msg = 'Hello world.'
server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587
server.ehlo()
server.starttls()
server.ehlo()
server.login('myname@gmail.com','mypass')
server.sendmail('myname@gmail.com','somename@somewhere.com',msg)
server.close()
I'm just trying to send an email from my gmail account. The script uses starttls because of gmail's requirement. I've tried this on two web hosts, 1and1 and webfaction. 1and1 gives me a 'connection refused' error and webfaction reports no error but just doesn't send the email. I can't see anything wrong with the script, so I'm thinking it might be related to the web hosts. Any thoughts and comments would be much appreciated.
EDIT: I turned on debug mode. From the output, it looks like it sent the message successfully...I just never receive it.
send: 'ehlo web65.webfaction.com\r\n'
reply: '250-mx.google.com at your service, [174.133.21.84]\r\n'
reply: '250-SIZE 35651584\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-STARTTLS\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250 PIPELINING\r\n'
reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84]
SIZE 35651584
8BITMIME
STARTTLS
ENHANCEDSTATUSCODES
PIPELINING
send: 'STARTTLS\r\n'
reply: '220 2.0.0 Ready to start TLS\r\n'
reply: retcode (220); Msg: 2.0.0 Ready to start TLS
send: 'ehlo web65.webfaction.com\r\n'
reply: '250-mx.google.com at your service, [174.133.21.84]\r\n'
reply: '250-SIZE 35651584\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-AUTH LOGIN PLAIN\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250 PIPELINING\r\n'
reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84]
SIZE 35651584
8BITMIME
AUTH LOGIN PLAIN
ENHANCEDSTATUSCODES
PIPELINING
send: 'AUTH PLAIN *****\r\n'
reply: '235 2.7.0 Accepted\r\n'
reply: retcode (235); Msg: 2.7.0 Accepted
send: 'mail FROM:<myname@gmail.com> size=12\r\n'
reply: '250 2.1.0 OK 4sm652580yxq.48\r\n'
reply: retcode (250); Msg: 2.1.0 OK 4sm652580yxq.48
send: 'rcpt TO:<myname@gmail.com>\r\n'
reply: '250 2.1.5 OK 4sm652580yxq.48\r\n'
reply: retcode (250); Msg: 2.1.5 OK 4sm652580yxq.48
send: 'data\r\n'
reply: '354 Go ahead 4sm652580yxq.48\r\n'
reply: retcode (354); Msg: Go ahead 4sm652580yxq.48
data: (354, 'Go ahead 4sm652580yxq.48')
send: 'Hello world.\r\n.\r\n'
reply: '250 2.0.0 OK 1240421143 4sm652580yxq.48\r\n'
reply: retcode (250); Msg: 2.0.0 OK 1240421143 4sm652580yxq.48
data: (250, '2.0.0 OK 1240421143 4sm652580yxq.48')
|
Have you tried constructing a valid message?
from email.MIMEText import MIMEText
msg = MIMEText('body')
msg['Subject'] = 'subject'
msg['From'] = "..."
msg['Reply-to'] = "..."
msg['To'] = "..."
|
Accepting email address as username in Django
|
Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.
Please advise, thank you.
|
For anyone else wanting to do this, I'd recommend taking a look at django-email-as-username which is a pretty comprehensive solution, that includes patching up the admin and the createsuperuser management commands, amongst other bits and pieces.
Edit: As of Django 1.5 onwards you should consider using a custom user model instead of django-email-as-username.
|
Python Access Data in Package Subdirectory
|
I am writing a python package with modules that need to open data files in a ./data/ subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system.
I've tried a variety of methods, but so far I have had no luck. It seems that most of the "current directory" commands return the directory of the system's python interpreter, and not the directory of the module.
This seems like it ought to be a trivial, common problem. Yet I can't seem to figure it out. Part of the problem is that my data files are not .py files, so I can't use import functions and the like.
Any suggestions?
Right now my package directory looks like:
/
__init__.py
module1.py
module2.py
data/
data.txt
I am trying to access data.txt from module*.py
Thanks!
|
The standard way to do this is with setuptools packages and pkg_resources.
You can lay out your package according to the following hierarchy, and configure the package setup file to point it your data resources, as per this link:
http://docs.python.org/distutils/setupscript.html#installing-package-data
You can then re-find and use those files using pkg_resources, as per this link:
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access
|
Unescape Python Strings From HTTP
|
I've got a string from an HTTP header, but it's been escaped.. what function can I use to unescape it?
myemail%40gmail.com -> myemail@gmail.com
Would urllib.unquote() be the way to go?
|
I am pretty sure that urllib's unquote is the common way of doing this.
>>> import urllib
>>> urllib.unquote("myemail%40gmail.com")
'myemail@gmail.com'
There's also unquote_plus:
Like unquote(), but also replaces plus signs by spaces, as required for unquoting HTML form values.
|
Convert a number to a list of integers
|
How do I write the magic function below?
>>> num = 123
>>> lst = magic(num)
>>>
>>> print lst, type(lst)
[1, 2, 3], <type 'list'>
|
You mean this?
num = 1234
lst = [int(i) for i in str(num)]
|
SQLAlchemy - Dictionary of tags
|
I have question regarding the SQLAlchemy. How can I add into my mapped class the dictionary-like attribute, which maps the string keys into string values and which will be stored in the database (in the same or another table as original mapped object). I want this add support for arbitrary tags of my objects.
I found the following example in SQLAlchemy documentation:
from sqlalchemy.orm.collections import column_mapped_collection, attribute_mapped_collection, mapped_collection
mapper(Item, items_table, properties={
# key by column
'notes': relation(Note, collection_class=column_mapped_collection(notes_table.c.keyword)),
# or named attribute
'notes2': relation(Note, collection_class=attribute_mapped_collection('keyword')),
# or any callable
'notes3': relation(Note, collection_class=mapped_collection(lambda entity: entity.a + entity.b))
})
item = Item()
item.notes['color'] = Note('color', 'blue')
But I want the following behavior:
mapper(Item, items_table, properties={
# key by column
'notes': relation(...),
})
item = Item()
item.notes['color'] = 'blue'
It is possible in SQLAlchemy?
Thank you
|
The simple answer is yes.
Just use an association proxy:
from sqlalchemy import Column, Integer, String, Table, create_engine
from sqlalchemy import orm, MetaData, Column, ForeignKey
from sqlalchemy.orm import relation, mapper, sessionmaker
from sqlalchemy.orm.collections import column_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
Create a test environment:
engine = create_engine('sqlite:///:memory:', echo=True)
meta = MetaData(bind=engine)
Define the tables:
tb_items = Table('items', meta,
Column('id', Integer, primary_key=True),
Column('name', String(20)),
Column('description', String(100)),
)
tb_notes = Table('notes', meta,
Column('id_item', Integer, ForeignKey('items.id'), primary_key=True),
Column('name', String(20), primary_key=True),
Column('value', String(100)),
)
meta.create_all()
Classes (note the association_proxy in the class):
class Note(object):
def __init__(self, name, value):
self.name = name
self.value = value
class Item(object):
def __init__(self, name, description=''):
self.name = name
self.description = description
notes = association_proxy('_notesdict', 'value', creator=Note)
Mapping:
mapper(Note, tb_notes)
mapper(Item, tb_items, properties={
'_notesdict': relation(Note,
collection_class=column_mapped_collection(tb_notes.c.name)),
})
Then just test it:
Session = sessionmaker(bind=engine)
s = Session()
i = Item('ball', 'A round full ball')
i.notes['color'] = 'orange'
i.notes['size'] = 'big'
i.notes['data'] = 'none'
s.add(i)
s.commit()
print i.notes
That prints:
{u'color': u'orange', u'data': u'none', u'size': u'big'}
But, are those in the notes table?
>>> print list(tb_notes.select().execute())
[(1, u'color', u'orange'), (1, u'data', u'none'), (1, u'size', u'big')]
It works!! :)
|
Qt and context menu
|
i need to create a context menu on right clicking at my window. But i really don't know what should i do. Are there any widgets or i must make it by my hands?
Programming language: Python
Graphical lib: Qt (PyQt).
|
I can't speak for python, but it's fairly easy in C++.
first after creating the widget you set the policy:
w->setContextMenuPolicy(Qt::CustomContextMenu);
then you connect the context menu event to a slot:
connect(w, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &)));
Finally, you implement the slot:
void A::ctxMenu(const QPoint &pos) {
QMenu *menu = new QMenu;
menu->addAction(tr("Test Item"), this, SLOT(test_slot()));
menu->exec(w->mapToGlobal(pos));
}
that's how you do it in c++ , shouldn't be too different in the python API.
EDIT: after looking around on google, here's the setup portion of my example in python:
self.w = QWhatever();
self.w.setContextMenuPolicy(Qt.CustomContextMenu)
self.connect(self.w,SIGNAL('customContextMenuRequested(QPoint)'), self.ctxMenu)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.