python

Concatenating two lists - difference between '+=' and extend()

I've seen there are actually two (maybe more) ways to concatenate lists in Python: One way is to use the extend() method: a = [1, 2] b = [2, 3] b.extend(a) the other to use the plus(+) operator: b += a Now I wonder: Which of those two options is the 'pythonic' way to do list concatenation and is there a difference between the two (...

Cleaning data which is of type URLField

I have a simple URLField in my model link = models.URLField(verify_exists = False, max_length = 225) I would like to strip the leading and trailing spaces from the field. I don't think I can do this in "clean_fieldname" or in the "clean" method. Do I need to sub-class the "URLField" and remove the spaces in to_python method? Is ther...

Python - Way to distinguish between item index in a list and item's contents in a FOR loop?

For instance, if I wanted to cycle through a list and perform some operation on all but the final list entry, I could do this: z = [1,2,3,4,2] for item in z: if item != z[-1]: print z.index(item) But instead of getting the output "...0 1 2 3," I'd get "...0 2 3." Is there a way to perform an operation on all but t...

How do you avoid this race condition in Python / Django / MySQL?

I have a model MyModel that has a field expiration_datetime. Every time a user retrieves an instance of MyModel I need to first check if it has expired or not. If it has expired, than I need to increment some counter, update others, and then extend the expiration_datetime to some time in the future. So the view would do something ...

How to properly store object reference in treemodel?

I'm trying to store an object reference in the rows of a treemodel so that I can access and modify the data in the underlying data structure. What would be the proper way to do this? The only way I've found so far to accomplish this is to inherit my data structure nodes from gobject, and then store a gobject column in each row. Is there ...

Python: int to binary stream element?

If you have a int and you wish to convert it to a single char string you can use the function chr() Is there a way to convert an int to a single char binary stream? e.g: >>> something(97) b'a' What is the something? ...

criticism this python code (crawler with threadpool)

Hi, how good this python code ? need criticism) there is a error in this code, some times script do print "ALL WAIT - CAN FINISH!" and freeze (no more actions are happend..) but i can't find reason why this happend? site crawler with threadpool: import sys from urllib import urlopen from BeautifulSoup import BeautifulSoup, SoupStrainer...

Sql Alchemy > TypeError: 'instancemethod' object does not support item assignment

Here's what I've got: from sqlalchemy import * from sqlalchemy.orm import * from web.models.card import * connectionString = "postgresql://www:www@localhost/prod" databaseEngine = create_engine(connectionString) sessionFactory = sessionmaker(autoflush = True, autocommit = False, bind = databaseEngine) session = sessionFactory() CardsCo...

Run all my doctests for all python modules in a folder without seeing failures because of bad imports

I've started integrating doctests into my modules. (Hooray!) These tend to be files which started as scripts, and are now are a few functions with CLI apps in the __name__=='__main__', so I don't want to put the running of the tests there. I tried nosetests --with-doctest, but get lots of failures I don't want to see, because some of ...

Which Python projects should I study to learn best practices

What are the best Python projects to study if one wants to look at the codebase and see how well-designed Python projects are structured and coded? Open source is preferred for obvious reasons, but they could be closed-source too. It could be interesting to see how the interface or API is designed. Small projects would be as interestin...

"python manage.py runserver" = cannot execute binary file error (django)

new one to me commend I'm running ubuntu 10.04 relatively fresh install on my laptop manually installed django 1.2.1 when I try to run inside of a virtualenv python manage.py **any command** I get the error "bash: /home/alvin/workspace/storm-guard/virtual_damage_restoration/bin/python: cannot execute binary file " I have done the fo...

SciPy Create 2D Polygon Mask

I need to create a numpy 2D array which represents a binary mask of a polygon, using standard Python packages. input: polygon vertices, image dimensions output: binary mask of polygon (numpy 2D array) (Larger context: I want to get the distance transform of this polygon using scipy.ndimage.morphology.distance_transform_edt.) Can any...

Rounding up with pennies in Python?

I am making a change program in python. The user must input a dollar amount and then the program will calculate the change in twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. I was instructed to use the round function for the pennies because If I input an amount of $58.79, the program tells me to give 3 pennies back w...

Mac OS X: Trouble with Local Django + PyDev install working with remote MySQL

I've got PyDev installed in Eclipse. I'm trying to play with Django. I'm got a remote MySQL database set up. I would really like to not install MySQL on my MacBook. Trying to set up the MySQL plugin for python, I get (djangotest)jeebus:MySQL-python-1.2.3 blah$ python setup.py clean sh: mysql_config: command not found Traceback (most r...

Format date with month name in polish, in python.

Is there an out of the box way to format in python (or within django templates), a date with full month name in accordance to polish language rules? I want to get: 6 września 2010 and not: >>> datetime.today().date().strftime("%d %B %Y") '06 wrzesień 2010' ...

python mysql configuration problem

Hi all, I'm trying to make django work on snow leopard. So far I've installed mysql 64 bit installed python 2.7 64 bit and installed django 1.2.1. Now I'm trying to install mysql-python-1.2.3; at the beginning I had problems because I hadn't installed the setup tool, having done that when try to install it by executing these command pyt...

How to hide the password in fabric when the command is printed out?

Say I have a fabfile.py that looks like this: def setup(): pwd = getpass('mysql password: ') run('mysql -umoo -p%s something' % pwd) The output of this is: [host] run: mysql -umoo -pTheActualPassword Is there a way to make the output look like this? [host] run: mysql -umoo -p******* Note: ...

Matplotlib: multiple y axes, grid lines applied to both?

I've got a Matplotlib graph with two y axes, created like: ax1 = fig.add_subplot(111) ax1.grid(True, color='gray') ax1.plot(xdata, ydata1, 'b', linewidth=0.5) ax2 = ax1.twinx() ax2.plot(xdata, ydata2, 'g', linewidth=0.5) I need grid lines but I want them to apply to both y axes not just the left one. The scales of each axes will diffe...

Why does the Python/C API crash on PyRun_SimpleFile?

I've been experimenting with embedding different scripting languages in a C++ application, currently I'm trying Stackless Python 3.1. I've tried several tutorials and examples, what few I can find, to try and run a simple script from an application. Py_Initialize(); FILE* PythonScriptFile = fopen("Python Scripts/Test.py", "r"); if(Pyth...

Why can't I assign to undeclared attributes of an object() instance but I can with custom classes?

Basically I want to know why this works: class MyClass: pass myObj = MyClass() myObj.foo = 'a' But this returns an AttributeError: myObj = object() myObj.foo = 'a' How can I tell which classes I can use undefined attributes with and which I can't? Thanks. ...