python

What's the best way to find the closest matching type to an existing type?

I've got a registry of classes and types in Python 2.5, like so: class ClassA(object): pass class ClassB(ClassA): pass MY_TYPES = { basestring : 'A string', int : 'An integer', ClassA : 'This is ClassA or a subclass', } I'd like to be able to pass types to a function, and have it look up the closest matching typ...

SQLAlchemy Obtain Primary Key With Autoincrement Before Commit

When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing? I would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned i...

Why do I get unexpected behavior in Python isinstance after pickling?

Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle: from __future__ import with_statement import pickle # Simple class definition class myclass(object): def __init__(self, data): self.data = d...

do you know of any python component(s) for syntax highlighting?

Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) . ...

Python function: Find Change from purchase amount

I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back. Would it be best to set up a dictionary? ...

Django Forms Newbie Question

Alright, I'm at a loss with the Django Forms, as the documentation just doesn't seem to quite cover what I'm looking for. At least it seems to come to a screeching halt once you get past the most rudimentary of forms. I'm more than willing to take a link to good documentation, or a link to a good book that covers this topic, as an answer...

Accessing a MySQL database from python.

I have been trying for the past several hours to find a working method of accessing a mysql database in python. The only thing that I've managed to get to compile and install is pyodbc but the necessary driver is not available for ppc leopard. I already know about this. UPDATE: I've gotten setuptools to install, but now MySQL-python ...

Another Django Forms : Foreign Key in Hidden Field

Another Django Form question. My form : class PlanForm(forms.ModelForm): owner = forms.ModelChoiceField(label="", queryset=Profile.objects.all(), widget=forms.HiddenInput()) etc... class Meta: model = Plan Owner, in the model, is a ForeignKey...

How to print tuples of unicode strings in original language (not u'foo' form)

I have a list of tuples of unicode objects: >>> t = [('亀',), ('犬',)] Printing this out, I get: >>> print t [('\xe4\xba\x80',), ('\xe7\x8a\xac',)] which I guess is a list of the utf-8 byte-code representation of those strings? but what I want to see printed out is, surprise: [('亀',), ('犬',)] but I'm having an inordinate amount o...

How to slice a list from an element n to the end in python?

Hi all, I'm having some trouble figuring out how to slice python lists, it is illustrated as follows: >>> test = range(10) >>> test [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> test[3:-1] [3, 4, 5, 6, 7, 8] >>> test[3:0] [] >>> test[3:1] [] >>> test [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] To my understanding, python slice means lst[start:end], and inclu...

What does re.compile(r'[[]]') match?

With Python's re module, why do the following act differently: >>> r = re.compile(r'[][]') >>> r.findall(r'[]') ['[', ']'] >>> r = re.compile(r'[[]]') >>> r.findall(r'[]') ['[]'] >>> r.findall(r'][') [] ...

Python and random keys of 21 char max

Hello, I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ? For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 cha...

Choosing and deploying a comet server.

I want to push data to the browser over HTTP without killing my django/python application. I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly). I've looked into the following engines: orbited cometd ejabberd jetty Has anyone had any experience...

.cgi problem with web server

The code #!/usr/bin/env python import MySQLdb print "Content-Type: text/html" print print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute(“SELECT name FROM books ORDER BY pub...

Unable to import python-mysqldb

I installed python-mysqldb using sudo apt-get install python-mysqldb I have tried to use it unsuccessfully. The following commands do not work in Python prompt: import python-mysqldb Or import mysqldb How can I solve this problem? ...

Python Reflection and Type Conversion

In Python, functions like str(), int(), float(), etc. are generally used to perform type conversions. However, these require you to know at development time what type you want to convert to. A subproblem of some Python code I'm trying to write is as follows: Given two variables, foo and bar, find the type of foo. (It is not known at ...

How to change cursor position of wxRichTextCtrl in event handler?

I have a RichTextCtrl in my application, that has a handler for EVT_KEY_DOWN. The code that is executed is the following : def move_caret(self): pdb.set_trace() self.rich.GetCaret().Move((0,0)) self.Refresh() def onClick(self,event): self.move_caret() event.Skip() rich is my RichTextCtrl. Here is what I would ...

Increment Page Hit Count in Django

I have a table with an IntegerField (hit_count), and when a page is visited (ie. http://site/page/3) I want record id 3 'hit_count' column in the database to increment by 1. The query should be like: update table set hit_count = hit_count + 1 where id=3 Can I do this with the standard Django Model conventions? Or should I just write th...

Unable to install Python without sudo access

I extracted, configured and used make for the installation package in my server. However, I could not use make install. I get the error [~/wepapps/python/Python-2.6.1]# make install /usr/bin/install -c python /usr/local/bin/python2.6 /usr/bin/install: cannot create regular file `/usr/local/bin/python2.6': Permission denied make: *** [a...

Python, PIL, crop problem

Can't seem to get crop working correctly, problem is, it crops a region of correct dimensions, but always from top left corner (0, 0), instead of from my passed coordinates. image = Image.open(input) region = image.crop((1000,400,2000,600) region.save(output) In image.py from PIL, method _ImageCrop I've printed out.. : print x0, y0, ...