Archive for March, 2007
March 27, 2007 at 1:10 am · tags: PyConIt Python
We finally did it! A bunch of eager people including myself managed to organize what’s going to be the first Italian Python Conference, ever.
It will be held in Florence, in the wonderful Tuscany on June the 9th and 10th, 2007.
If you happen to be Italian and also interested in Python keep an eye on the official website. If, better, you’re also interested in taking an active part and speak to the fellow pythonista in the country read the instructions for the Call for Papers on pycon.it.
It’s gonna be cool so bookmark the website and check in the near future for further info.
Obviously the long term aim is to spread the Python word across to increase utilization, the community and maybe, why not, also the job offerings.
Python, Conference, Italy. Enough said!
March 19, 2007 at 11:57 pm · tags: DotNET
Roger Johansson just said:
ASP.NET. Oh my, where do I start. As long as the default Visual Studio controls spew out nonsense markup that is completely dependent on JavaScript to work, well, there will be no progress among the myriad sites created by the drag-and-drop cowboys that call themselves programmers. This needs to be fixed ASAP.
It reminds me of something I ranted about 4 years ago: avoid ASP.NET.
So, let’s see. Four years (or four ages, is the same on the web) and they’re still at the same spot
Oh my.
March 18, 2007 at 3:58 pm · tags: Python Python SVN
- dir() can be customised with __ dir __ special method:
Python 2.6a0 (trunk:54427, Mar 18 2007, 14:13:42)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
>>> class A(object):
… pass
…
>>> dir(A())
[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__doc__’, … ]
>>> class B(object):
… def __dir__(self):
… return []
…
>>> dir(B())
[]
>>> class C(object):
… def __init__(self):
… self.attrs = {’special_attr’: ‘got it’}
… def __getattr__(self, attr):
… if attr in self.attrs:
… return self.attrs[attr]
… def __dir__(self):
… return self.attrs.keys()
…
>>> c = C()
>>> c.special_attr
‘got it’
>>> dir(c)
[’special_attr’]
urllib2 raises URLError instead of OSError if you try to access something with the file:// protocol and it fails.
urllib raises IOError if the server’s response contains an invalid HTTP status line.
%VAR% and “~user” are expanded correctly in Windows with ntpath.expandvars()!
pdb gains a run command to restart the debugger with optional different arguments.
ctypes module has a c_bool type.
You can get the documentation of a thing with pydoc.render_doc():
>>> import pydoc
>>> pydoc.doc(‘os’) # this pages the doc
>>> pydoc.render_doc(‘os’) # this prints on stdout
‘Python Library Documentation: module os\n\nN\x08NA\x08AM\x08ME\x08E\n os - OS routines for Mac, NT, or Posix depending on what system we\’re on.\n\nF\x08FI\x08IL\x08LE\x08E\n … ‘
- Finally the timeit module accept callables in addition of strings. See repeat() and timeit() for details:
>>> import timeit
>>> print timeit.repeat(lambda: xrange(100))
[0.64829111099243164, 0.63839888572692871, 0.63987302780151367]
>>> print timeit.repeat(lambda: range(100))
[2.9226858615875244, 2.9176130294799805, 2.9172840118408203]
>>> print timeit.timeit(lambda: xrange(100))
0.637830018997
>>> print timeit.timeit(lambda: range(100))
2.88584208488
- By default textwrap.wrap() drops whitespaces at the end (or the start) of the text, now you can avoid that and preserve all the text:
>>> import textwrap
>>> print textwrap.wrap(“A “* 100)
[‘A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A’, ‘A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A’, ‘A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A’]
>>> print textwrap.wrap(“A “* 100, drop_whitespace=False)
[‘A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A ‘, ‘A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A ‘, ‘A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A ‘]
see that every string in the second example has its trailing whitespace.
- os.walk() can follow symlinks now:
rhymes@groove ~ % ll temp total 8
drwxr-xr-x 3 rhymes rhymes 102B Mar 18 14:49 a/
lrwxr-xr-x 1 rhymes rhymes 5B Mar 18 14:49 link@ -> /Users/rhymes/Documents
>>> import os
>>> for root, dirs, files in walk(‘temp’):
… print root, dirs, files
…
temp [‘a’, ‘link’] []
temp/a [] [‘foo’]
>>> for root, dirs, files in walk(‘temp’, followlinks=True):
… print root, dirs, files
…
temp [‘a’, ‘link’] []
temp/a [] [‘foo’]
temp/link [‘.parallels-vm-directory’, …]
read the doc as usual for details.
webbrowser has been fixed to use GNOME, KDE, Windows default browsers.
os.path module has a function to retrieve the relative path of paths:
>>> os.path.relpath(‘/Library/Frameworks’)
‘../../../../Library/Frameworks’
>>> os.path.relpath(‘/Library/Frameworks’, start=‘..’)
‘../../../Library/Frameworks’
March 18, 2007 at 2:09 pm · tags: Django Python
Update: this post is for version 0.96 only since the trick is now outdated.
As many of you already the trunk version of Django carries a brand new infrastructure to handle HTML forms providing rendering capabilities and validation.
Its name is newforms but I guess it will soon become just forms replacing the current framework which will be removed in Django 1.0. The documentation is in evolution and right now does not cover all the stuff.
One of the top questions about newforms is how to upload a file and validate it in some way. It is imperative for our example to hook into the newforms’ validation system otherwise we won’t gain any advantage. Let’s move on, then.
A couple of days ago I read all the previous threads on django-users about the subject but nothing really came up so I dug into the bare code and I hacked some very straightforward (not sure if it’s a best practice) to handle the case.
In our sample we’re going to upload an image to a Django website validating the content (we want to be sure it’s an image), its width and height (we’re lazy and we want to spare CPU cycles instead of resizing on the fly) and its size.
Read the rest of this entry »
March 16, 2007 at 6:00 pm · tags: Django Python
Antonio Cangiano is asking for help and ideas. Being himself the former author of the Rails tools for the IBM DB2 DBMS he’s searching for input for the development of a set of tools and drivers for Python, Django an DB2.
I think it’s a great idea having that kind of support in Django, even maybe if I won’t be using DB2 anytime soon. So, if you do care about Django and Python send your ideas to him and we’ll all make one enterprisey step ahead
Python, Django and DB2: we need your input
March 12, 2007 at 1:18 am · tags: Python Unicode
There’s a lot of stuff on the web about Unicode and Python but this is the best tutorial I’ve found, ever:
All About Python and Unicode
March 11, 2007 at 1:27 pm · tags: Python Python SVN
There’s a slight change in the behavior of os.path.splitext because of a bug current versions of Python do have:
Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
>>> from os.path import splitext
>>> splitext(‘.cshrc’)
(”, ‘.cshrc’)
becomes:
Python 2.6a0 (trunk:54262, Mar 10 2007, 18:06:14)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
>>> from os.path import splitext
>>> splitext(‘.cshrc’)
(‘.cshrc’, ”)
You can now pass a TestRunner instance to unittest.main() and run doctest from the command line against your beloved Python with python -m doctest file.py.
Another new feature is open() in ZipFile objects allowing you to read a file inside an archive directly:
>>> import zipfile
>>> zf = zipfile.ZipFile(‘README.zip’)
>>> f = zf.open(‘README’)
>>> print f.read()
Hello
The tuple() object is great to store struct-like data but it’s accessible only through numeric indexes so in Python 2.6 you can use also named tuples like:
>>> from collections import NamedTuple
>>> Point = NamedTuple(‘Point’, ‘x y’)
>>> p = Point(10, 5)
>>> p.x
10
>>> p.y
5
It behaves like a normal tuple so you can use it everywhere. See the full documentation.
There’s also a bunch of fixes or additions in networking-related modules like support for LMTP in smtplib, HTTP_REFERER support in CGIHTTPServer and more.
As usual, the very source of information for what’s new are the SVN logs or the NEWS file.
March 7, 2007 at 5:09 pm · tags: Pinder Python
Pinder is a straightforward API to interface with Campfire , the web chat application from 37Signals.
It’s basically a port of Tinder but maybe in the future will go on separate ways.
Pinder allows you to create rooms, delete them, speak from a remote client and more. For example:
>>> room = campfire.find_room_by_name(‘Jonz Room’)
>>> print room.users()
set([u‘Alice’])
or
>>> print campfire.users()
set([u‘Alice’, u‘Bob’])
which gets the list of the users talking in each room of the subdomain.
will send the message to the chat room so you can speak too.
There’s more like creating and deleting rooms, toggling guest access, locking the room etc.
See the usage documentation and the API documentation for details.
You can install the latest release with:
$ easy_install pinder
or
download it from here: http://dev.oluyede.org/download/pinder/
This is the first public release.
March 7, 2007 at 1:42 pm · tags: Django Python
Sometimes you need to get down to the core and make your code faster. One technique to speed up things is performance analysis through profiling.
Python 2.5 has revamped its support for profiling with the addition of cProfile which is (the name says all) a C-based version of the profile module. It’s definitely better than hotshot (which has been somewhat fixed in the latest version).
Django has a custom handler which enables mod_python powered apps to be profiled (with hotshot) without monkey patching the codebase.
What about internal webserver anyway?
There’s a wiki page about that. You simply have to patch django/core/management.py with this patch and Django will generate a handful of .prof files in /tmp or whatever each time you invoke the webserver. Then you have to read the stats with hotshot.stats.load or you can use gather_profile_stats.py and collect them all in aggregated profile files.
Sadly I didn’t get cProfile to work with Django because it lacks of a method returning the result of the profiled callable like the hotshot’s runcall but I didn’t spent much time on that so I guess the hack is just around the corner.
That’s it.
HTH