[ANN] markup.py 1.8

2012-02-18 Thread Daniel Nogradi
A new release of markup.py is available at http://markup.sourceforge.net/

This new release is compatible with both python 2 and 3.

What is markup.py?

Markup.py is an intuitive, light weight, easy-to-use, customizable and
pythonic HTML/XML generator. The only goal is quickly writing HTML/XML
segments or whole documents programatically if you need anything more
than that you probably want to look for a templating engine.


-- 
interior | space | design | http://www.annazeibig.com | 3d | living | deco
-- 
http://mail.python.org/mailman/listinfo/python-list


python autoconf macro for building ming extension

2007-10-03 Thread Daniel Nogradi
It might be slightly off topic here but couldn't find a more suitable
place for this question:

I'm trying to build the python binding for ming -- http://ming.sf.net
-- but for some reason the python macro for autoconf -- python.m4 --
doesn't seem to detect my python installation correctly. The strange
thing is that it seemingly detects everything correctly, but a final
check still fails. I have the python 2.5 source distribution installed
to /usr/local the standard location.

Configuring ming fails with:

checking for python... /usr/local/bin/python
checking for python2.5... (cached) /usr/local/bin/python
checking for a version of Python = '2.1.0'... yes
checking for the distutils Python package... yes
checking for Python include path... -I/usr/local/include/python2.5
checking for Python library path... -L/usr/local/lib/python2.5 -lpython2.5
checking for Python site-packages path... /usr/local/lib/python2.5/site-packages
checking python extra libraries... -lpthread -ldl -lutil
checking python extra linking flags... -Xlinker -export-dynamic
checking consistency of all components of python development environment... no
configure: error:
  Could not link test program to Python. Maybe the main Python library has been
  installed in some non-standard library path. If so, pass it to configure,
  via the LDFLAGS environment variable.
  Example: ./configure LDFLAGS=-L/usr/non-standard-path/python/lib
  
   ERROR!
   You probably have to install the development version of the Python package
   for your distribution.  The exact name of this package varies among them.
  


and all variables above are correct. It apparently found

PYTHON_CPPFLAGS=-I/usr/local/include/python2.5
PYTHON_LDFLAGS=-L/usr/local/lib/python2.5 -lpython2.5
PYTHON_SITE_PKG=/usr/local/lib/python2.5/site-packages
PYTHON_EXTRA_LIBS=-lpthread -ldl -lutil
PYTHON_EXTRA_LDFLAGS=-Xlinker -export-dynamic

all correctly, yet the final check fails. I even tried configuring
with PYTHON_NOVERSIONCHECK and LDFLAGS=-L/usr/local/lib/python2.5 and
gave the above environment variables manually but still the same final
check fails.

Apparently it's not a ming but an autoconf issue. Anyone familiar with
python.m4?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: first, second, etc line of text file

2007-07-26 Thread Daniel Nogradi
  A very simple question: I currently use a cumbersome-looking way of
  getting the first, second, etc. line of a text file:
 
  for i, line in enumerate( open( textfile ) ):
  if i == 0:
  print 'First line is: ' + line
  elif i == 1:
  print 'Second line is: ' + line
  ...
  ...
 
  I thought about f = open( textfile ) and then f[0], f[1], etc but that
  throws a TypeError: 'file' object is unsubscriptable.
 
  Is there a simpler way?

 If all you need is sequential access, you can use the next() method of
 the file object:

 nextline = open(textfile).next
 print 'First line is: %r' % nextline()
 print 'Second line is: %r' % nextline()
 ...

 For random access, the easiest way is to slurp all the file in a list
 using file.readlines().

Thanks! This looks the best, I only need the first couple of lines
sequentially so don't need to read in the whole file ever.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tix.Tk() on Mac Intel

2007-07-26 Thread Daniel Nogradi
On 7/26/07, Alan [EMAIL PROTECTED] wrote:
 Hi List!

 I have I Macbook Pro Intel running OSX 10.4.10.

 I downloaded Python 2.5 and tried
 TclTkAquaBI-8.4.10.0.dmg, but I got:

 Traceback (most recent call last):
  File stdin, line 1, in module
  File
 /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py,
 line 210, in __init__
self.tk.eval('package require Tix')
 _tkinter.TclError: no suitable image found.  Did find:
/Library/Tcl/Tix8.4/libTix8.4.dylib: mach-o, but wrong architecture

 Which make sense since tcltkaqua is released only for PPC. Googling a
 bit, since tcltkaqua stopped development, I found they recommended
 ActiveTcl, but Tix is not included in the package.

 So removing tcltkaqua and ActiveTcl, when trying Tix.Tk() I got:
  Tix.Tk()
 Traceback (most recent call last):
  File stdin, line 1, in module
  File
 /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py,
 line 210, in __init__
self.tk.eval('package require Tix')
 _tkinter.TclError: can't find package Tix

 The only way I got Tix.Tk() working so far was using Fink but I want
 the nice aqua visual for python. Is there any way of getting it
 working?

 I would appreciate any help here.
 Many thanks in advance.
 Cheers,
 Alan
 --
 http://mail.python.org/mailman/listinfo/python-list


You might want to look into this thread on the same issue:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/878b8a1d9e6d92ce/6f257a1c60ab50f2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: first, second, etc line of text file

2007-07-25 Thread Daniel Nogradi
Thanks all! I think I will stick to my original method because the
files can be quite large and without reading the whole file into
memory probably enumerate( open( textfile ) ) is the only way to
access an arbitrary Nth line.
-- 
http://mail.python.org/mailman/listinfo/python-list


first, second, etc line of text file

2007-07-25 Thread Daniel Nogradi
A very simple question: I currently use a cumbersome-looking way of
getting the first, second, etc. line of a text file:

for i, line in enumerate( open( textfile ) ):
if i == 0:
print 'First line is: ' + line
elif i == 1:
print 'Second line is: ' + line
...
...

I thought about f = open( textfile ) and then f[0], f[1], etc but that
throws a TypeError: 'file' object is unsubscriptable.

Is there a simpler way?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: standalone module

2007-07-15 Thread Daniel Nogradi
 I want to create a standalone program ( an exe file ) from my python files
 which works on Windows and Linux.

 Could you please tell me how to do that?


The same executable should work on both linux and windows? Not
possible. But see:

http://mail.python.org/pipermail/python-list/2007-July/448658.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to install pygame package?

2007-07-14 Thread Daniel Nogradi
 There seems to be some problem. For the tar version, initial steps
 execute OK, but after typing:
 [EMAIL PROTECTED] pygame-1.7.1release]# ./configure
 bash: ./configure: No such file or directory

 So i don't hav a configure file? What should i do now?

Sorry, instead of ./configure do this:

python setup.py install

It's a python package after all :)

But first I would recommend reading http://pygame.org/install.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to call bluebit...

2007-07-13 Thread Daniel Nogradi
 how to import bluebit matrik calculator that result of singular value
 decomposition (SVD) in python programming..

I'm not really sure I understand you but you might want to check out scipy:

http://scipy.org/

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to install pygame package?

2007-07-13 Thread Daniel Nogradi
 Im working in red hat linux 9.0. I've downloaded the pygame package
 but i dont know how to install it. If anybody has the time to detail
 the steps sequentially... thanx!

 P.S. I've downloaded both the tar and the rpm packages...

First you can try the rpm package:

su
(give the root password)
rpm -i the-package-you-downloaded.rpm

Or with the tar package:

tar xzvf the-package-you-downloaded.tar.gz
cd pygame-x.x.x (the name of the created directory)
./configure
make
su
(give the root password)
make install

HTH.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic method

2007-07-11 Thread Daniel Nogradi
  I have an issue I think Python could handle. But I do not have the
  knowledge
  to do it.
 
  Suppose I have a class 'myClass' and instance 'var'. There is function
  'myFunc(..)'. I have to add (or bind) somehow the function to the
  class, or
  the instance. Any help, info or point of reference is wellcome
 
  How about this (note the first argument 'self' which is the instance
  itself in the second case):
 
 
 
  def method_for_instance( message ):
 print message
 
  def method_for_class( self, message ):
 print message
 
  class myClass( object ):
 pass
 
  inst = myClass( )
  inst.method = method_for_instance
 
  inst.method( 'hello' )

 This won't work as expected:

 class Bidule(object):
def __init__(self, name):
  self.name = name

 def greet(self, who):
print hello %s, my name is %s % (who, self.name)

 b = Bidule('Bruno')
 b.greet = greet
 b.greet('Daniel')

 =
 Traceback (most recent call last):
File stdin, line 1, in module
File /tmp/python-23258Nq5.py, line 10, in module
  b.greet('Daniel')
 TypeError: greet() takes exactly 2 arguments (1 given)


Well, I thought the name method_for_instance and method_for_class are
clear enough that if you want to 'attach' one of them to an instance
then method_for_instance should be used :)
And method_for_instance has only one argument and so will work as in
the example I gave (I guess you just overlooked them).


 The point is that Python functions are descriptor objects that, when
 looked up, return a (bound or unbound) method object wrapping
 themselves. So to attach functions as method *on a per-instance basis*,
 you either need to use new.instancemethod (as explained by Alex), or
 directly use the descriptor protocol, ie:

 b.greet = greet.__get__(b)
 b.greet('Daniel')
 = hello Daniel, my name is Bruno

 Note that you don't need this to attach a function as method to a class
 - the descriptor protocol will then JustWork(tm).


I agree that in general the solution explained by Alex and you is better.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: standalone executables

2007-07-10 Thread Daniel Nogradi
 I need a reference to get all the programs which used to package Python
 programs into standalone executables files.
  Would you help me?


windows: http://www.py2exe.org/
mac: http://cheeseshop.python.org/pypi/py2app/
linux: http://wiki.python.org/moin/Freeze
linux/windows: http://python.net/crew/atuining/cx_Freeze/

HTH.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic method

2007-07-10 Thread Daniel Nogradi
 I have an issue I think Python could handle. But I do not have the knowledge
 to do it.

 Suppose I have a class 'myClass' and instance 'var'. There is function
 'myFunc(..)'. I have to add (or bind) somehow the function to the class, or
 the instance. Any help, info or point of reference is wellcome

How about this (note the first argument 'self' which is the instance
itself in the second case):



def method_for_instance( message ):
print message

def method_for_class( self, message ):
print message

class myClass( object ):
pass

inst = myClass( )
inst.method = method_for_instance

inst.method( 'hello' )

myClass.method = method_for_class

inst = myClass( )
inst.method( 'hello' )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 15 Exercises to Know A Programming Language

2007-07-03 Thread Daniel Nogradi
   Write a program that takes as its first argument one of the words
   'sum,' 'product,' 'mean,' or 'sqrt'  and for further arguments a
   series of numbers. The program applies the appropriate function to
   the series.
 
   My solution so far is this:
 
  http://dpaste.com/13469/
 
   I would really like some feedback. Is this a good solution? is it
   efficient? robust? what could be improved? any not looking for a
   revised solution, hints on what to improve are also very welcome.
 
  Don't use `eval()` if it is not absolutely necessary.  Especially if the
  input comes from a user it's a security hole.  `float()` is the function
  to use here.
 
  `mean()` does not work as you try to divide a list by a number.
 

 Thanks for the feedback. I have posted a revised version here (http://
 dpaste.com/13474/) where mean works. The reason I use eval is I want
 it to work for complex numbers too, but I guess i could check for the
 presence of a j in the arguments instead.


Hi, if I invoke your program without arguments an uncaught exception
is raised. Wouldn't it be better to inform the user that an argument
is expected?

See http://docs.python.org/tut/node10.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python 3.0 or 3000 ....is it worth waiting??? Newbie Question

2007-07-03 Thread Daniel Nogradi
 Hi
 I'm considering learning Python...but with the python 3000 comming
 very soon, is it worth waiting for?? I know that the old style of
 coding python will run parallel with the new, but I mean, its going to
 come to an end eventually.

 What do you think??
 Chris


99% of what you would learn from python 2.x will be useful for python 3.0.

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Memory leak in PyQt application

2007-07-01 Thread Daniel Nogradi
 Python 2.5.1
 Boost.Python
 Qt 4.2.2
 SIP 4.6
 PyQt 4.2
 WinXp

 I've a memory leak in a PyQt application and no idea how to find it. What
 happens in the application ?

  From QWindow a QDialog is called on a button pressed() signal, that
 instantiate a QThread and waits for it. If the thread has finished, the
 QDialog
 closes.

 I've stipped down everything that nothing more happens (to me obviously).
 Boost.Python is used to wrap a C++ Lib (used in the thread). Every time
 memory
 usage increases for ~70 KB.

 Sometimes the application crash on closing QWindow. (QtCore.dll)

 - One thing I ask me is weather garbage collection is done in the PyQt main
 loop?

 What hints do you have to find the leak?


Have a look at valgrind: http://valgrind.org/

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Voluntary Abstract Base Classes

2007-06-29 Thread Daniel Nogradi
Hi list,

Well, the short question is: what are they? I've read Guido's python
3000 status report on
http://www.artima.com/weblogs/viewpost.jsp?thread=208549 where he
mentions ABC's but don't quite understand what the whole story is
about.

Anyone has good use cases?

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Voluntary Abstract Base Classes

2007-06-29 Thread Daniel Nogradi
  Well, the short question is: what are they? I've read Guido's python
  3000 status report on
  http://www.artima.com/weblogs/viewpost.jsp?thread=208549 where he
  mentions ABC's but don't quite understand what the whole story is
  about.

 The story is at PEP 3119:
 http://www.python.org/dev/peps/pep-3119/

Thanks, I overlooked that somehow.

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python live environment on web-site?

2007-06-21 Thread Daniel Nogradi
  I was wondering if there was a python-live-environment available on a
  public web-site similar to the ruby-live-tutorial on
 
  http://tryruby.hobix.com/
 
  I would prefer something which allows to paste small scripts into a
  text-field, to run them on the server, and to be able to read the
  produced output of the script.
 
  I searched using google but didn't come across such a site. However, I
  imagine there must be at least one


 Crunchy.


As far as I remember the pypy people also put together a publicly
available python console in javascript. Actually it's a whole xterm I
think and one can start python in there.

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dive into Python 5.5

2007-06-13 Thread Daniel Nogradi
 class UserDict:
 def __init__(self, dict=None):
 self.data = {}
 if dict is not None: self.update(dict)

 I just don't understant this code, as it is not also mention in the
 book. the update is a method of a dict right? in my understanding the
 last statement should be self.data.update(dict).

 someone please explain to me what happen where?

You are right, this code will not work, and your suggestion is a reasonable one.

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Goto

2007-06-13 Thread Daniel Nogradi
 How does one effect a goto in python? I only want to use it for debug.
 I dasn't slap an if clause around the portion to dummy out, the
 indentation police will nab me.


http://entrian.com/goto/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: google maps api for py?

2007-05-30 Thread Daniel Nogradi
 I see that the weapon of choice for google maps is javascript...  Is
 there anything for python?

I wrote the following for finding the latitude/longitude of a
location. You need to set the variable 'key' to the actual key you got
from google.

(Indentation might get mixed up on the way.)

HTH,
Daniel


###
#   gmaps.py
###

import urllib
from time import sleep

key = here_goes_your_key

def location2latlong( query, key=key ):
Get the ( latitute, longitude ) coordinates corresponding
to the query. If something goes wrong return None.

output = 'csv'

params = { }
params[ 'key' ] = key
params[ 'output' ] = output
params[ 'q' ] = query

params = urllib.urlencode( params )

try:
f = urllib.urlopen( http://maps.google.com/maps/geo?%s; % params )
except IOError:
# maybe some local problem at google? let's try again
sleep( 3 )
try:
f = urllib.urlopen( http://maps.google.com/maps/geo?%s; % params )
except IOError:
# okay we give up
return None

response = f.read( ).split(',')
f.close( )

try:
status = response[0]
accuracy = response[1]
latitude = response[2]
longitude = response[3]
except:
return None

if status != '200':
return None
else:
return latitude, longitude

if __name__ == '__main__':
import sys

try:
q = sys.argv[1]
except:
print 'Usage: python gmaps.py query'
sys.exit( 1 )

r = location2latlong( q )
if r is not None:
print r
else:
print 'Something went wrong.'

###
###
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Resize image NO PIL!!

2007-05-29 Thread Daniel Nogradi
 I have created an image hosting site and when a user uploads an image,
 I want a service to run on the server to create a few thumbnails while
 the user does other things.

 My stupid host (pair.com) doesn't have PIL installed and I'm too much
 of a stupid newbie to figure out how to get it to work with them
 (access denied while installing it, of course).

 Also, they don't have any python interface setup for GD.

 Anyway, I don't know what my options are.  I'm thinking:

 1) Find another host with mod_python, PIL, and other Python goodies
 2) use PHP to create the thumbnails
 3) Open the images into a buffer and try to do the calculations
 myself

 I'm thinking I might have to go with 1.

 I want the script to run as a service so I don't know how well number
 2 would work and I certainly don't want number 3 (on a time-line
 here).

Why don't you put PIL where your modules are? You are surely allowed
to upload your own python modules somewhere where you can access them
(and import them) so you can put PIL into the same place and happily
import them just as any other module you wrote. You might need to find
out what the architecture of the machine is (as far as I remember PIL
has some C extensions) and compile PIL for that architecture.

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: model browser

2007-05-23 Thread Daniel Nogradi
  Are there other options I overlooked?
 
  Daniel

 There is a CRUD template for TG:
 http://docs.turbogears.org/1.0/CRUDTemplate

 Might be what you're looking for.

I was looking for something that is not based on a framework such as
django or tg (and not on sqlalchemy either, but on sqlobject). It
seems actually that catwalk is quite easy to decouple from tg and thus
can be turned into a stand alone model browser that only depends on
sqlobject.
-- 
http://mail.python.org/mailman/listinfo/python-list


model browser

2007-05-20 Thread Daniel Nogradi
Hi list,

I'm looking for an sqlobject based model browser with a web interface
(is this the thing called CRUD these days?). Searching all over the
place turned up of course django's automatic admin interface and
turbogears' catwalk but I wouldn't want to buy into any of these two
frameworks because they are too complicated and complex. I don't know
about django but since tg is sqlobject based catwalk might still be a
good candidate if it can be decoupled from the rest of tg. By looking
at the source of catwalk it seems that this decoupling requires quite
some work; did anyone do something like this? Or does anyone know if
catwalk was originally written for tg or was general purpose before
and became integrated into tg later?

Are there other options I overlooked?

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: model browser

2007-05-20 Thread Daniel Nogradi
And before you ask, yes, I did read
http://mail.python.org/pipermail/python-list/2007-May/440337.html but
there was nothing beyond django/tg :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Web Programming - looking for examples of solid high-traffic sites

2007-05-18 Thread Daniel Nogradi
 For example, it HAS been published elsewhere that YouTube uses lighttpd,
 not Apache: http://trac.lighttpd.net/trac/wiki/PoweredByLighttpd.

How do you explain these, then:

http://www.youtube.com/results.xxx
http://www.youtube.com/results.php
http://www.youtube.com/results.py

Just wondering,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Web Programming - looking for examples of solid high-traffic sites

2007-05-18 Thread Daniel Nogradi
   For example, it HAS been published elsewhere that YouTube uses lighttpd,
   not Apache: http://trac.lighttpd.net/trac/wiki/PoweredByLighttpd.
  
   How do you explain these, then:
  
   http://www.youtube.com/results.xxx
   http://www.youtube.com/results.php
   http://www.youtube.com/results.py
 
  Server signature is usually configurable.

 Yeah, but I don't know why it's configured it that way.  A good example
 of a question that looks perfectly appropriate for YouTube's OSCON
 session.

Let us know what they say! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Web Programming - looking for examples of solid high-traffic sites

2007-05-18 Thread Daniel Nogradi
   For example, it HAS been published elsewhere that YouTube uses lighttpd,
   not Apache: http://trac.lighttpd.net/trac/wiki/PoweredByLighttpd.
  
   How do you explain these, then:
  
   http://www.youtube.com/results.xxx
   http://www.youtube.com/results.php
   http://www.youtube.com/results.py
 
  Server signature is usually configurable.

 Yeah, but I don't know why it's configured it that way.  A good example
 of a question that looks perfectly appropriate for YouTube's OSCON
 session.

Actually, the fact that http://www.youtube.com/results.php returns
legitimate content might be explainable by the fact that youtube was
started as a PHP app so they might provide this URL for backward
compatibility although today there is no PHP at all. See the abstract
of Mike Solomon's OSCON talk: YouTube began as a small PHP
application. [...]
http://conferences.oreillynet.com/cs/os2007/view/e_sess/13435
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending a JavaScript array to Python script?

2007-05-17 Thread Daniel Nogradi
 Just wondering if there is any way of sending a JavaScript array to a
 Python cgi script? A quick Google search didn't turn up anything
 useful.


Simplejson is what you want:  http://cheeseshop.python.org/pypi/simplejson

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] markup.py 1.7

2007-05-17 Thread Daniel Nogradi
A new release is available for markup.py, a module for generating
HTML/XML output painlessly and practically without any learning curve.
The goal of markup.py is to be able to quickly put together documents
in an ad hoc basis so if you need anything for production look for
something else, e.g. ElementTree. Downloads are here:
http://markup.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I count the number of spaces at the left end of a string?

2007-05-16 Thread Daniel Nogradi
 I don't know exactly what the first non-space character is. I know the
 first non-space character will be  * or an alphanumeric character.

How about:

 mystring = 'ksjfkfjkfjds   '
 print len( mystring ) - len( mystring.lstrip( ) )
4


HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cPickle.dumps differs from Pickle.dumps; looks like a bug.

2007-05-16 Thread Daniel Nogradi
  I've found the following strange behavior of cPickle. Do you think
  it's a bug, or is it by design?
 
  Best regards,
  Victor.
 
  from pickle import dumps
  from cPickle import dumps as cdumps
 
  print dumps('1001799')==dumps(str(1001799))
  print cdumps('1001799')==cdumps(str(1001799))
 
  outputs
 
  True
  False
 
  vicbook:~ victor$ python
  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.
 quit()
 
  vicbook:~ victor$ uname -a
  Darwin vicbook 8.9.1 Darwin Kernel Version 8.9.1: Thu Feb 22 20:55:00
  PST 2007; root:xnu-792.18.15~1/RELEASE_I386 i386 i386

 If you unpickle though will the results be the same? I suspect they
 will be. That should matter most of all (unless you plan to compare
 objects' identity based on  their pickled version.)

The OP was not comparing identity but equality. So it looks like a
real bug, I think the following should be True for any function f:

if a == b: f(a) == f(b)

or not?

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cPickle.dumps differs from Pickle.dumps; looks like a bug.

2007-05-16 Thread Daniel Nogradi
I've found the following strange behavior of cPickle. Do you think
it's a bug, or is it by design?
   
Best regards,
Victor.
   
from pickle import dumps
from cPickle import dumps as cdumps
   
print dumps('1001799')==dumps(str(1001799))
print cdumps('1001799')==cdumps(str(1001799))
   
outputs
   
True
False
   
vicbook:~ victor$ python
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.
   quit()
   
vicbook:~ victor$ uname -a
Darwin vicbook 8.9.1 Darwin Kernel Version 8.9.1: Thu Feb 22 20:55:00
PST 2007; root:xnu-792.18.15~1/RELEASE_I386 i386 i386
  
   If you unpickle though will the results be the same? I suspect they
   will be. That should matter most of all (unless you plan to compare
   objects' identity based on  their pickled version.)
 
  The OP was not comparing identity but equality. So it looks like a
  real bug, I think the following should be True for any function f:
 
  if a == b: f(a) == f(b)
 
  or not?
 
 
 Obviously not, in the general case. random.random(x) is the most
 obvious example, but there's any number functions which don't return
 the same value for equal inputs. Take file() or open() - since you get
 a new file object with new state, it obviously will not be equal even
 if it's the same file path.

Right, sorry about that, posted too quickly :)
I was thinking for a while about a deterministic

 For certain inputs, cPickle doesn't print the memo information that is
 used to support recursive and shared data structures. I'm not sure how
 it tells the difference, perhaps it has something to do with
 refcounts. In any case, it's an optimization of the pickle output, not
  a bug.

Caching?

 from cPickle import dumps
 dumps('0') == dumps(str(0))
True
 dumps('1') == dumps(str(1))
True
 dumps('2') == dumps(str(2))
True


 dumps('9') == dumps(str(9))
True
 dumps('10') == dumps(str(10))
False
 dumps('11') == dumps(str(11))
False


Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asyncore Help?

2007-05-14 Thread Daniel Nogradi
 I am working on the networking code for a small Multiplayer RPG I'm
 working on. I currently have some basic code using threads, but it
 seems like asyncore would be far better suited for my needs. However,
 I have trouble finding a solid example for what I need. Python.org and
 other sites provide simple examples, but they appear more intended for
 servers that simply send one peice of data to the client.

 I want to have a server program that is willing to accept commands
 sent from the client, and repeatedly wait for data and respond.
 Maintaining a long term connection until the client is done playing.

 Besides this I am also stuck with dealing with TCP data streams. I can
 receive and send the data (using threads, not yet with asynocore), but
 I am unsure how to deal with the streamlike nature of TCP (and would
 prefer to use TCP over UDP). I would like to have it so that the
 client sends the server a command (such as update position), and then
 the data, and have the server update that information on its side
 accordingly.

 While basic socket work was rather easy to deal with, this has proved
 significantly more difficult. Are there any good free sources for
 information on Asyncore, and dealing with TCP?

The twisted project might also be a good place for anything related to
python and networking: http://twistedmatrix.com/trac/
-- 
http://mail.python.org/mailman/listinfo/python-list


elementtree and entities

2007-05-13 Thread Daniel Nogradi
Hi list,

How does one prevent elementtree converting  to amp; (and similarly
for other entities)?

 from xml.etree import ElementTree as et
 x = et.Element( 'test' )
 x.text = ''
 et.tostring( x )
'testamp;/test'

Sometimes I would like to have the output 'test/test'

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: elementtree and entities

2007-05-13 Thread Daniel Nogradi
  How does one prevent elementtree converting  to amp; (and similarly
  for other entities)?
 
  from xml.etree import ElementTree as et
  x = et.Element( 'test' )
  x.text = ''
  et.tostring( x )
  'testamp;/test'
 
  Sometimes I would like to have the output 'test/test'
 

 elementtree is for processing xml. If you want to output something which
 isn't xml then you'll have to use a different library or mess about with
 the xml after it has been generated:

et.tostring(x).replace('amp;', '')

 does what you want, but you won't be able to parse it again with anything
 which expects xml.

Thanks for the reply, I'll just live with replace then.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic subclassing ?

2007-05-12 Thread Daniel Nogradi
 I've got an instance of a class, ex :

 b=gtk.Button()

 I'd like to add methods and attributes to my instance b.
 I know it's possible by hacking b with setattr() methods. But i'd
 like to do it with inheritance, a kind of dynamic subclassing,
 without subclassing the class, only this instance b !

 In fact, i've got my instance b, and another class MoreMethods

 class MoreMethods:
 def  sayHello(self):
   print hello

 How could i write ...

 b = b + MoreMethods

 so b will continue to be a gtk.Button, + methods/attributs of
 MoreMethods (it's what i call dynamic inheritance) ...so, things
 like this should work :

 - b.set_label(k)
 - b.sayHello()

 I can't find the trick, but i'm pretty sure it's possible in an easy
 way.

How about:

class MoreMethods:
def  sayHello(self):
print hello

class myButton( gtk.Button, MoreMethods ):
pass

b = myButton( )

isinstance( b, gtk.Button )  # True
b.sayHello( )  # hello


Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic subclassing ?

2007-05-12 Thread Daniel Nogradi
   I've got an instance of a class, ex :
 
   b=gtk.Button()
 
   I'd like to add methods and attributes to my instance b.
   I know it's possible by hacking b with setattr() methods. But i'd
   like to do it with inheritance, a kind of dynamic subclassing,
   without subclassing the class, only this instance b !
 
   In fact, i've got my instance b, and another class MoreMethods
 
   class MoreMethods:
   def  sayHello(self):
 print hello
 
   How could i write ...
 
   b = b + MoreMethods
 
   so b will continue to be a gtk.Button, + methods/attributs of
   MoreMethods (it's what i call dynamic inheritance) ...so, things
   like this should work :
 
   - b.set_label(k)
   - b.sayHello()
 
   I can't find the trick, but i'm pretty sure it's possible in an easy
   way.
 
  How about:
 
  class MoreMethods:
  def  sayHello(self):
  print hello
 
  class myButton( gtk.Button, MoreMethods ):
  pass
 
  b = myButton( )
 
  isinstance( b, gtk.Button )  # True
  b.sayHello( )  # hello

 yes, but it needs to recreate an instance (of mybutton) ...
 i can't do that, in my context.
 The only things i've got is my instance b (which can be whatever
 object).
 i'd like to add methods/attributes to this instance, by adding a
 heritage of another class.

I think that is not possible, at least in a simple way (there might be
a complicated way of messing with the MRO). Please anyone correct me
if I was wrong.

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Newbie] design question

2007-05-12 Thread Daniel Nogradi
 Suppose I have class ShoppingCart which has one method called buy(),
 and class Buyer who has one reference to ShoppingCart...  Can I also
 have method buy() in class Buyer, which will then called
 ShoppingCard.buy(), and also do some other stuff?  Is this legal
 design pattern, have methods with same name?

Yes, something like this is perfectly fine.

class ShoppingCart( object ):
def buy( self ):
print 'buy in shoppingcart'

class Buyer( object ):
def __init__( self, cart ):
self.cart = cart

def buy( self ):
print 'buy in buyer'
self.cart.buy( )
print 'some extra stuff'

acart = ShoppingCart( )
abuyer = Buyer( cart=acart )
abuyer.buy( )


HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File modes

2007-05-10 Thread Daniel Nogradi
 After reading a file is it possible to write to it without first
 closing it? I tried opening with 'rw' access and re-winding. This does
 not seem to work unless comments are removed.


 Also, does close force a flush?

 Thanks,

 jh

 #~~

 f = open('c:\\tempMaxq\\incidents.txt', 'rw')
 s = f.read()
 lst = s.split()
 incId = []
 incId.extend([lst.pop(), lst.pop()])
 #f.close()
 #f = open('c:\\tempMaxq\\incidents.txt', 'w')
 #f.seek(0)
 for el in lst:
 f.write(el + ' ')
 f.close()


Please see the documentation of the function open( ):
http://python.org/doc/lib/built-in-funcs.html It says that the modes
can only be 'r', 'w', 'a', 'r+', 'w+', 'a+' and possibly a 'b' or 'U'
appended to these. So if you open it with 'rw' it will be interpreted
as 'r'. For example this will not work:

f = open( 'myfile', 'rw' )
f.write( 'hello' )
f.close( )

because python thinks you want to open 'myfile' in 'r' mode. I guess I
agree that the thrown exception IOError: [Errno 9] Bad file descriptor
is not very informative in this case.

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mod Python Question

2007-05-08 Thread Daniel Nogradi
 I am very new to Python and Mod_Python and I am running into what
 looks like a caching problem.

 I have the following code:
 ---
 from mod_python import apache
 from folder import Messenger

 def handler(req):

 msg = Messenger(req):

 # using req.write

 msg.write(hello world)

 return apache.OK
 -
 So the Messenger class has the method write which calls req.write.
 This will output hello world in the browser. However, when I go into
 Messenger and change the method name from write to anything else, it
 still works. It is as if the class is being cached. I have deleted pyc
 but that has not done anything either. What is going on?


This has come up on the mod_python list a number of times, please see
these threads, among others:

http://www.modpython.org/pipermail/mod_python/2004-October/016567.html
http://www.modpython.org/pipermail/mod_python/2004-February/014959.html
http://www.modpython.org/pipermail/mod_python/2005-April/017859.html
http://www.modpython.org/pipermail/mod_python/2005-July/018619.html

and especially these articles:

http://www.dscpl.com.au/wiki/ModPython/Articles/ModuleImportingIsBroken
http://www.dscpl.com.au/wiki/ModPython/Articles/BasicsOfModuleImporting

Actually the mod_python list is very responsive one to mod_python
questions probably much more than this (the python list). You can sign
up here:

http://mailman.modpython.org/mailman/listinfo/mod_python

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __getattr__ and __getattribute__

2007-05-08 Thread Daniel Nogradi
 i find it difficult to understand the difference between the magic methods
 __getattr__ and __getattribute__
 and so donot know when to use former or later.

From the docs:

__getattr__(self, name)  Called when an attribute lookup has not found
the attribute in the usual places (i.e. it is not an instance
attribute nor is it found in the class tree for self).

__getattribute__(self, name) Called unconditionally to implement
attribute accesses for instances of the class.

Please see http://docs.python.org/ref/new-style-attribute-access.html
and http://docs.python.org/ref/attribute-access.html

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite for mac?

2007-05-03 Thread Daniel Nogradi
   Does sqlite come in a mac version?
 
   The interface (pysqlite) is part of the python 2.5 standard library
   but you need to install sqlite itself separately (as far as I
   remember) fromwww.sqlite.org
 
  http://developer.apple.com/documentation/MacOSX/Conceptual/OSX_Techno...
 

 I downloaded pysqlite, ran the setup script, and tested the
 installation and everything worked fine.  However, if I try to import
 either sqlite, sqlite2, or sqlite3 into a python program, I get an
 error saying there's no such module.

 I assume that means pysqlite cannot see the installation of SQlite
 that came preinstalled on my mac.  My python book says to download the
 SQlite source where automatic code generation has already been
 performed.  I did that.  Then my book says says to follow the
 instructions in the README file.  However, the download only has two
 files:  sqlite3.c and sqlite3.h.  As a result, I don't know what to
 do.

If all tests ran fine then pysqlite can see your sqlite installation.
How are you importing sqlite? It's usually something like from
pysqlite2 import dbapi2 as sqlite not simply import sqlite. If you
go to the test directory where everything works you can see how those
modules import it and that should definitely work for you as well.

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What do people use for code analysis.

2007-05-02 Thread Daniel Nogradi
 Lots of code, calls to, calls by, inheritance, multiple tasks, etc.

 What do people use to figure out what's happening?

This is a pretty cool project just for that:

http://codeinvestigator.googlepages.com/codeinvestigator

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite for mac?

2007-05-01 Thread Daniel Nogradi
 Does sqlite come in a mac version?


The interface (pysqlite) is part of the python 2.5 standard library
but you need to install sqlite itself separately (as far as I
remember) from www.sqlite.org

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: zipfile: grabbing whole directories

2007-05-01 Thread Daniel Nogradi
 The built in zipfile.write doesn't seem to like  taking a directory instead
 of  a filename.

 for example:
 for each in listofdir:
 archive.write(each)

 blows up when one of the items listed in listofdir is a subdirectory.

   File /usr/local/lib/python2.4/zipfile.py, line 405, in write
 fp = open(filename, rb)

 is there a mode or a '-r' style param I am missing?

I guess what you really want is recursively archive every file in a
directory and its subdirectories. If that is the case you can use
os.walk to iterate over all such files so you can archive all of them
while the directory structure will be preserved.

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite for mac?

2007-05-01 Thread Daniel Nogradi
  I'm using python 2.4.4 because the download said there were more mac
  modules available for 2.4.4. than 2.5, and I can't seem to locate a
  place to download sqlite for mac.
 
  I it comes on OS X Tiger, and possibly earlier versions as well (it's
  used as an index for Mail.app)..  You just need to download and
  install the pysqlite libraries.

 The system sqlite btw (which reports itself as version 3.1.3), is not
 the same as what is included in Python 2.5.   Will somebody please
 say what version of sqlite is supported by Python 2.5

I'm using sqlite 3.3.11 with python 2.5 (on linux) but I guess some
earlier versions will also work.

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite for mac?

2007-05-01 Thread Daniel Nogradi
   Does sqlite come in a mac version?
 
  The interface (pysqlite) is part of the python 2.5 standard library
  but you need to install sqlite itself separately (as far as I
  remember) fromwww.sqlite.org
 
  Daniel

 I'm using python 2.4.4 because the download said there were more mac
 modules available for 2.4.4. than 2.5, and I can't seem to locate a
 place to download sqlite for mac.

If you use python 2.4.4 you can install the pysqlite module from
http://www.initd.org/tracker/pysqlite/wiki/pysqlite (this is the
interface that is included in python 2.5, you need to install sqlite
itself, probably from source, with any python version).

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I/O Operations .....

2007-04-30 Thread Daniel Nogradi
 I am parsing an XML file and sending the output to two files.The
 code asks the user to enter the input file,something like:

 file_input = raw_input(Enter The ODX File Path:)
 input_xml = open(file_input,'r')

   Now suppose the user enters the path as :
 C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.odx.xml

  I have 2 output files to which i have to redirect the output.The
 output file name should be same as input file in the same path ( the
 extension has to change to a format ini which is basically text file
 opened using notepad).Eg..
 output files should be :
 C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.ini,   and,
 C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.xls

If you only would like to know how to write files, this might help:

content1 = ..
content2 = ...

f = open( 'file1', 'w' )
f.write( content1 )
f.close( )

f = open( 'file2', 'w' )
f.write( content2 )
f.close( )


HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I/O Operations .....

2007-04-30 Thread Daniel Nogradi
   I am parsing an XML file and sending the output to two files.The
   code asks the user to enter the input file,something like:
 
   file_input = raw_input(Enter The ODX File Path:)
   input_xml = open(file_input,'r')
 
 Now suppose the user enters the path as :
   C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.odx.xml
 
I have 2 output files to which i have to redirect the output.The
   output file name should be same as input file in the same path ( the
   extension has to change to a format ini which is basically text file
   opened using notepad).Eg..
   output files should be :
   C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.ini,   and,
   C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.xls
 
  If you only would like to know how to write files, this might help:
 
  content1 = ..
  content2 = ...
 
  f = open( 'file1', 'w' )
  f.write( content1 )
  f.close( )
 
  f = open( 'file2', 'w' )
  f.write( content2 )
  f.close( )
 
  HTH,
  Daniel- Hide quoted text -
 
  - Show quoted text -

  Hi,
 File writing can be done in that way,but my query is
 something different.I have to rename the output file by default with
 input file name(only changing the extension.


Maybe something like this will help (on Linux, Windows is similar):

 from os import path
 f = '/tmp/hello.xls'
 path.splitext( f )
('/tmp/hello', '.xls')
 path.dirname( f )
'/tmp'
 path.basename( f )
'hello.xls'


Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Could zipfile module process the zip data in memory?

2007-04-29 Thread Daniel Nogradi
 I made a C/S network program, the client receive the zip file from the
 server, and read the data into a variable. how could I process the
 zipfile directly without saving it into file.
 In the document of the zipfile module, I note that it mentions the
 file-like object? what does it mean?

 class ZipFile( file[, mode[, compression[, allowZip64]]])
  Open a ZIP file, where file can be either a path to a file (a
 string) or a file-like object.

Yes it is possible to process the content of the zipfile without
saving every file:

[untested]

from zipfile import ZipFile
from StringIO import StringIO

zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' )
for name in zipp.namelist( ):
content = zipp.read( name )
s = StringIO( )
s.write( content )
# now the file 'name' is in 's' (in memory)
# you can process it further
# 
s.close( )
zipp.close( )


HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Could zipfile module process the zip data in memory?

2007-04-29 Thread Daniel Nogradi
   I made a C/S network program, the client receive the zip file from the
   server, and read the data into a variable. how could I process the
   zipfile directly without saving it into file.
   In the document of the zipfile module, I note that it mentions the
   file-like object? what does it mean?
 
   class ZipFile( file[, mode[, compression[, allowZip64]]])
Open a ZIP file, where file can be either a path to a file (a
   string) or a file-like object.
 
  Yes it is possible to process the content of the zipfile without
  saving every file:
 
  [untested]
 
  from zipfile import ZipFile
  from StringIO import StringIO
 
  zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' )
  for name in zipp.namelist( ):
  content = zipp.read( name )
  s = StringIO( )
  s.write( content )
  # now the file 'name' is in 's' (in memory)
  # you can process it further
  # 
  s.close( )
  zipp.close( )
 
  HTH,
  Daniel
 Thanks!
 Maybe my poor english makes you confusion:-). The client receive the
 zip file data from the server, and keep these data as a variable, not
 as a file in harddisk. such as zipFileData, but the first argument
 of the ZipFile is filename. I would like to let the ZipFile() open
 the file from zipFileData directly but not file in harddisk

 zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' )
   ^ I don't have this file, all its data
 is in a variable.

Well, as you correctly pointed out in your original post ZipFile can
receive a filename or a file-like object. If the zip archive data is
in zipFileData then you might do:

from StringIO import StringIO
from zipfile import ZipFile

data = StringIO( )
data.write( zipFileData )
data.close( )

zipp = ZipFile( data )
.


and continue in the same way as before.

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if __name__ == 'main': passing an arg to a class objec

2007-04-27 Thread Daniel Nogradi
 The lines

 if __name__ == 'main':
someClass().fn()

 appear at the end of many examples I see. Is this to cause a .class
 file to be generated?

Python doesn't generate .class files, and the example you mean is
probably more like

if __name__ == '__main__':
.whatever

which causes the whatever block to be executed when the program is run
from the command line (as opposed to being imported).

 The last line of the sample below has a string parameter. When I
 mimicked this I got an error stating that the class constructor did
 not take an arg, which seems correct.

 Thanks,

 gtb


 # Generated by MaxQ [com.bitmechanic.maxq.generator.CompactGenerator]
 from CompactTest import CompactTest

 class MaxQTest(CompactTest):
 # Recorded test actions.
 def runTest(self):
 self.msg('Test started')

 # ^^^ Insert new recordings here.  (Do not remove this line.)


 # Code to load and run the test
 if __name__ == 'main':
 MaxQTest('MaxQTest').Run()


It's hard to say what MaxQTest takes as an argument without seeing the
code. If you post more details it might be easier to help you, but in
any case this may be useful: http://python.org/doc/tut/

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re-ocurring Events

2007-04-26 Thread Daniel Nogradi
 A bit more of a complex one this time, and I thought I'd get your opinions
 on the best way to achieve this. Basically I'm looking for a way to describe
 a re-occurring event, like a calendar event or appointment I guess. I'm
 likely to use an XML file for the definition of the events, but imagine I've
 got an event that looks something like this.

 event start=2007-01-01 12:00:00 end=2007-01-01 15:00:00 repeat=daily
 /

 Now what I want to do is be able to build a class which has a function like
 'getCurrentEvent()' which will return any events that should be occurring at
 that time. So if the current system time and date is 2007-01-03 13:00:00
 then it will return THAT event to me, but if it was say 2007-01-03 16:00:00
 then it would not, as the event isn't 'due' to occur at that time. Make
 sense?

 What's the best way of handling this? I'm really a little lost as to how I
 might get started, checking a static date time isn't a problem, it's when it
 comes to these re-occurring events that I struggle a little. The idea is
 that I would have 5 core repetitions, none, daily, weekly, monthly and
 annually.

This will not solve all your problems, but a very convenient way of
handling XML is the element tree module (that comes with python 2.5):
http://docs.python.org/lib/module-xml.etree.ElementTree.html

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If Dict Contains...

2007-04-25 Thread Daniel Nogradi
 Looking to build a quick if/else statement that checks a dictionary for a
 key like follows.

 If myDict contains ThisKey:

 Do this...

 Else

 Do that...



 Thats the best way of doing this?


if key in myDict:
Do this.
else:
Do that


HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Now()

2007-04-25 Thread Daniel Nogradi
 I'm using the following function 'str (now)' to place a date time stamp into
 a log file, which works fine, however it writes the stamp like this.

 2007-04-25 11:06:53.873029

 But I need to expel those extra decimal places as they're causing problems
 with the application that parses the log data, all I need is something like
 this:

 2007-04-25 11:06:53

Please see http://docs.python.org/lib/module-time.html

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-24 Thread Daniel Nogradi
[Alex]
 When cash is involved, it's important to avoid even the
 slightest hint of a suggestion of a suspicion of a conflict of interest

I propose the non-PSF sponsored Grand Prize For Successfully Squeezing
4 Of's In A Single Sentence should be received by Alex Martelli this
month :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Socket exceptions aren't in the standard exception hierarchy

2007-04-23 Thread Daniel Nogradi
  2. File D:\Python24\lib\socket.py, line 295, in read
  data = self._sock.recv(recv_size)
  error: (10054, 'Connection reset by peer')
 
  That looks like M$ Windows version of UNIX/Linux error number 54
  (pretty much all Windows socket errors are UNIX number+1)
 
  Errors coming from Windows may not be mapped to specific Python
  exceptions, but rather to some general error conditions. {hypothesis} As
  such, the Windows errors may not match what UNIX/Linux report.
 
 
   Actually, that's not what's happening. The socket module is
  explicitly raising socket.error in C code.  It's not an OSError or
  a WindowsError, although the text makes it look like one.
 
   The problem is not that socket errors aren't entirely portable.
  It's that they're not even in the Python exception hierarchy.
  See http://docs.python.org/lib/module-exceptions.html;.
  They have their own hierarchy, which starts at socket.error.
  All built-in exceptions were supposed to be converted to the
  standard exception hierarchy back before Python 2.0, but these
  weren't.
 
   Either they should be under IOError, or there should be
  NetworkError under EnvironmentError, and they should be under
  that.  NetworkError, alongside IOError in the hierarchy,
  would be useful.  All the things that go wrong in networking
  belong under there.  Socket-level errors, SSL/TLS-level errors,
  and HTTP/FTP/etc. level errors all belong under NetworkError.
 
   This has to be fixed before PEP 352, when the exception
  hierarchy is enforced, or the socket exceptions won't even work
  right.
 
  John:
 
  Where did you get this information? If true it would certainly need to
  be logged as a bug, but under Windows on 2,4 I see
 
issubclass(socket.gaierror, Exception)
  True
   
 
  and the same under Cygwin 2.5. I am presuming most other users will see
  the same thing.
 
  regards
   Steve

  Ah.  socket.error is a subclass of Exception, but not
 of StandardError.

issubclass(socket.error,StandardError)

 is False.


On linux, python 2.5:

 import socket
 issubclass(socket.error,Exception)
True
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionaries and dot notation

2007-04-22 Thread Daniel Nogradi
  This may be pretty obvious for most of you:
 
  When I have an object (an instance of a class Foo) I can access
  attributes via dot notation:
 
  aFoo.bar
 
  however when I have a dictionary
 
  aDict = {bar:something}
 
  I have to write
 
  aDict[bar]
 
  What if I want to create a datastructure that can be used in dot
  notation without having to create a class, i.e. because those objects
  have no behavior at all?
 
  I know that accessing an instance variable via bracket notation would
  really have to be written as:
 
  aFoo.__dict__['bar']
 
  but this does not bring me any further, because I would still have to
  plug in that __dict__ thing into my datastructure, which leads us to
  the same question as above.
 
  Can anyone tell me what I am missing here?


What's wrong with creating a dummy class?

class data:
pass

mydata = data( )
mydata.foo = 'foo'
mydata.bar = 'bar'

print mydata.foo
print mydata.bar



Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionaries and dot notation

2007-04-22 Thread Daniel Nogradi
  This may be pretty obvious for most of you:
 
  When I have an object (an instance of a class Foo) I can access
  attributes via dot notation:
 
  aFoo.bar
 
  however when I have a dictionary
 
  aDict = {bar:something}
 
  I have to write
 
  aDict[bar]
 
  What if I want to create a datastructure that can be used in dot
  notation without having to create a class, i.e. because those objects
  have no behavior at all?

 A class inheriting from dict and implementing __getattr__ and
 __setattr__ should do the trick...


It can do the trick but one has to be careful with attributes that are
used by dict such as update, keys, pop, etc. Actually it's noted in a
comment at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668
why the whole idea (attribute access of dictionaries) is a bad idea
and I tend to agree.

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: serializable object references

2007-04-22 Thread Daniel Nogradi
 Is it possible to convert an object into a string that identifies the
 object in a way, so it can later be looked up by this string.
 Technically this should be possible, because things like

 __main__.Foo instance at 0xb7cfb6ac

 say everything about an object. But how can I look up the real object,
 when I only have this string?

 I know such a thing can be achieved with a dictionary that holds
 reference-object pairs. Is there another way?


There is the pickle module for serializing objects into strings:
http://docs.python.org/lib/module-pickle.html

If you need to store objects and later look them up by some key I
would recommend using a database. There are plenty:
http://docs.python.org/lib/persistence.html

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Styled Output

2007-04-21 Thread Daniel Nogradi
 I'm running a program of mine from Linux bash script and it currently
 outputs status messages to the command prompt, but they all look a little
 boring to say the least, it'll be like this.

[snip]

 And perhaps have the word 'success' in green, or red for 'failed' and things
 like that, just to make it a little more presentable to the user.


You might find that urwid, a console user interface library, meets
your needs: http://excess.org/urwid/

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Styled Output

2007-04-21 Thread Daniel Nogradi
  I'm running a program of mine from Linux bash script and it currently
  outputs status messages to the command prompt, but they all look a little
  boring to say the least, it'll be like this.

 [snip]

  And perhaps have the word 'success' in green, or red for 'failed' and
 things
  like that, just to make it a little more presentable to the user.

Something like this might also help on linux:


def blue( text ):
print '\033[1m' + text + '\033[0m'

blue( 'this will be blue' )

See http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Threads -

2007-04-19 Thread Daniel Nogradi
 Can you please suggest a technique in Python where we can spawn few number
 of worker threads and later map them to a function/s to execute individual
 Jobs.

Have a look at the threading module:
http://docs.python.org/lib/module-threading.html

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python un-plugging the Interpreter

2007-04-19 Thread Daniel Nogradi
 Hi All,
  I was thinking about the feasbility of adjusting Python as a
 compiled language. Being said that I feel these are the following advantages
 of doing so --
  1) Using the powerful easy-to -use feature of Python programming language
 constructs.
  2) Making the program to run at par with the compiled version of C/C++
 program- this is the main benefit which can be derived out of this.
  3) Highly re-use existing Python code for High performance application.
  4) Acheive true parallelism and performance by getting rid of the
 middle-man Interpreter and GIL.

  I know this must be appearing like a foolish idea. But I would like to know
 the opinion of people who might have thought about it.


Have a look at pypy: http://codespeak.net/pypy/dist/pypy/doc/news.html
Especially the statement: Rumors have it that the secret goal is
being faster-than-C which is nonsense, isn't it?

Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array{uint32}

2007-04-18 Thread Daniel Nogradi
 I have a function that returns a array{uint32}, is there any way to output
 that to screen in a more user friendly format? At the moment when I print it
 by itself it appears as [65541L], which isn't much used to anyone.

I'm not sure I understand your question precisely but this might help:

 mylist = [65541L]
 mylist
[65541L]
 mylist[0]
65541L
 int(mylist[0])
65541

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deleting or Empty a File

2007-04-17 Thread Daniel Nogradi
 I'm looking to clear those log files we were discussing earlier chaps,


 What the best method to do this? Delete the file completely? Or just empty
 its content?


If you just want to delete the content of a file but keep it with 0
length you can do:

f = open( 'myfile', 'w' )# or open( 'myfile', 'wb' )
f.close( )

Since you mentioned log files, you might want to look at the logging module:

http://docs.python.org/lib/module-logging.html

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


string methods of a str subclass

2007-04-16 Thread Daniel Nogradi
I am probably misunderstanding some basic issue here but this
behaviour is not what I would expect:



Python 2.4 (#1, Mar 22 2005, 21:42:42)
[GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2
Type help, copyright, credits or license for more information.
 class mystr( str ):
... pass
...
 x = mystr( 'x' )
 isinstance( x, mystr )
True
 isinstance( x.strip( ), mystr )
False



Why is the strip( ) method returning something that is not a mystr
instance? I would expect all methods operating on a string instance
and returning another string instance to correctly operate on a mystr
instance and return a mystr instance. How would I achieve something
like this without manually copying all string returning methods from
str and stuffing the result to mystr( ) before returning?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string methods of a str subclass

2007-04-16 Thread Daniel Nogradi
  Why is the strip( ) method returning something that is not a mystr
  instance? I would expect all methods operating on a string instance
  and returning another string instance to correctly operate on a mystr
  instance and return a mystr instance.

 Why would you expect that?
 Would you expect the __str__ and__repr__ methods also to return a mystr
 instance? If not those, then which other ones might also be excluded?
 Is x.encode('zip') still a mystr instance or an encoded byte-string?

Okay, good point, thanks.

  How would I achieve something
  like this without manually copying all string returning methods from
  str and stuffing the result to mystr( ) before returning?

 You don't without wrapping all the affected methods. It doesn't need to
 involve manual copying though: you have a programming language available so
 just write a list of method names and then some code to wrap them
 automatically.

Yes, this is in fact what I am doing, using __getattr__ and such. Thanks again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lists and Tuples and Much More

2007-04-12 Thread Daniel Nogradi
 And the last example brings up another question.  What's the deal with a
 tupple that has a list in it such as:

 my_tupple = (1, 2, 3, 4, 5, [6, 7, 8, 9])

 Now I read somewhere that you could change the list inside that tupple.  But
 I can't find any documentation that describes HOW to do it.  The only things
 I CAN find on the subject say, Don't do it because its more trouble than
 it's worth.  But that doesn't matter to me, because I want to know
 everything.

You could change the list inside your tuple like this:

 my_tupple = (1, 2, 3, 4, 5, [6, 7, 8, 9])
 my_tupple[5].append(10)
 my_tupple
(1, 2, 3, 4, 5, [6, 7, 8, 9, 10])



 Now there comes append.  I read everywhere that append only add's 1 element
 to the end of your list.  But if you write:
  my_list = [1, 2, 3, 4, 5, 6]
  my_list.append([7, 8, 9, 10])
  my_list
 [1, 2, 3, 4, 5, 6, [7, 8, 9, 10]]

 Is that because list's, no matter what they contain, are counted as 1
 element?

Yes.

 And how would you sort the list that's in the list?  I guess that goes in
 conjunction with the section above, but still:
  my_list = [6, 4, 3, 5, 2, 1]
  my_list.append([7, 9, 8, 10])
  my_list.sort()
  my_list
 [1, 2, 3, 4, 5, 6, [7, 9, 8, 10]]

How about:

 my_list = [6, 4, 3, 5, 2, 1]
 my_list.append([7, 9, 8, 10])
 my_list[6].sort()
 my_list
[6, 4, 3, 5, 2, 1, [7, 8, 9, 10]]


HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Binary To File

2007-04-12 Thread Daniel Nogradi
 Is there an easy way to take binary data and build it into a file? Generally
 this will be BLOB data drawn from a database, the data will be for jpg
 images, I want to take the blob data and build it into a physical .jpg file.



 Is there a simple function for doing this in python? Like binary2file() or
 something along those lines?

myblob = . # let's say you got it from your database somehow
myjpeg = open( 'image.jpg', 'w' )
myjpeg.write( myblob )
myjpeg.close( )


Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing Problems

2007-04-03 Thread Daniel Nogradi
  I have just started learning python.I need to parse an XML file
 and present the contents in a particular format.The format is called
 as ini file.I have written some code.A section of the format needs
 the data to be present in format as given below:

 [Services]
 supported=0x10,0x1A,0x3B,0x20,0x27,0x28,0x34,0x36,0x3E,0xA2,0xA5,0x2D,
 0x22,0xA9,0x04,0xAA,0xAE

 My code for this section parses the xml file and gives :
 [Services]
 Supported=['0x3e', '0x28', '0x3b', '0x22', '0x20', '0x27', '0xaa',
 '0x10', '0xae', '0x34', '0x36', '0x2d', '0xa9', '0xa5', '0x4', '0xa2',
 '0x1a']

 {forget the numericals matching}.As you can see there
 are single quotes around numericals ,which is not desired .I think the
 problem lies in me using a list for storing and later printing out
 values.I have attached few lines of code,not sure how clear it can be
 to you:

 for l in range(0,len(ser_par),
 1):
 if
 ser_par[l].getAttribute('Semantics')==u'serviceId':
 if
 tag_exists(ser_par[l].childNodes,'VALUE'):
 val =
 ser_par[l].getElementsByTagName('VALUE')
 value =
 str(val[0].getAttribute('value'))
 valu = hex(int(value))
 rval.append(valu)
 ser_par_num = ser_par_num + 1
 prim_num = prim_num + 1

 service_num = service_num + 1
 variant_num = variant_num + 1
 ser = list(set(rval))

 print \n[Services]
 print Supported=+str(ser)

   How can i get rid of those single quotes.


mylist = ['0x3e', '0x28', '0x3b', '0x22', '0x20', '0x27', '0xaa',
'0x10', '0xae', '0x34', '0x36', '0x2d', '0xa9', '0xa5', '0x4', '0xa2',
'0x1a']

','.join( mylist )

This will give you:

0x3e,0x28,0x3b,0x22,0x20,0x27,0xaa,0x10,0xae,0x34,0x36,0x2d,0xa9,0xa5,0x4,0xa2,0x1a


Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ISO programming projects

2007-04-01 Thread Daniel Nogradi
 I'm looking for a collection of useful programming projects, at
 the hobbyist level.

 My online search did turn up a few collections (isolated projects
 are less useful to me at the moment), but these projects are either
 more difficult than what I'm looking for (e.g. code a C compiler)
 or not terribly useful to the average person (e.g. a function that
 efficiently computes the n-th Fibonacci number).

 Any pointers would be much appreciated.

 kj



http://wiki.python.org/moin/CodingProjectIdeas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: YouTube showing repr() of a tuple

2007-03-29 Thread Daniel Nogradi
 Thought this might amuse some of you:

 http://youtube.com/results?search_query=korect+my+speling

 I'd heard that YouTube uses Python, but it's fun to see proof of that,
 even if it comes in the form of a minor bug.


But their web frontend is (probably) in php:

http://youtube.com/results.php?search_query=korect+my+speling
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Other classes in a module

2007-03-25 Thread Daniel Nogradi
 Can an instance of a class in a module, in any simple way find out which
 other classes that exists in said module ?


# module x ##
class c1:
pass

class c2:
pass
###


Python 2.5 (r25:51908, Nov  1 2006, 11:42:37)
[GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2
Type help, copyright, credits or license for more information.
 import types
 import x
 for i in dir(x):
... if type(getattr(x,i)) is types.ClassType:
... print Hey, '%s' is a class! % i
...
Hey, 'c1' is a class!
Hey, 'c2' is a class!



It might be not exactly what you want but maybe still helps.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On text processing

2007-03-24 Thread Daniel Nogradi
  I'm in a process of rewriting a bash/awk/sed script -- that grew to
  big -- in python. I can rewrite it in a simple line-by-line way but
  that results in ugly python code and I'm sure there is a simple
  pythonic way.
 
  The bash script processed text files of the form:
 
  ###
  key1value1
  key2value2
  key3value3
 
  key4value4
  spec11  spec12   spec13   spec14
  spec21  spec22   spec23   spec24
  spec31  spec32   spec33   spec34
 
  key5value5
  key6value6
 
  key7value7
  more11   more12   more13
  more21   more22   more23
 
  key8value8
  ###
 
  I guess you get the point. If a line has two entries it is a key/value
  pair which should end up in a dictionary. If a key/value pair is
  followed by consequtive lines with more then two entries, it is a
  matrix that should end up in a list of lists (matrix) that can be
  identified by the key preceeding it. The empty line after the last
  line of a matrix signifies that the matrix is finished and we are back
  to a key/value situation. Note that a matrix is always preceeded by a
  key/value pair so that it can really be identified by the key.
 
  Any elegant solution for this?


 My solution expects correctly formatted input and parses it into
 separate key/value and matrix holding dicts:


 from StringIO import StringIO

 fileText = '''\
  key1value1
 key2value2
 key3value3

 key4value4
 spec11  spec12   spec13   spec14
 spec21  spec22   spec23   spec24
 spec31  spec32   spec33   spec34

 key5value5
 key6value6

 key7value7
 more11   more12   more13
 more21   more22   more23

 key8value8
 '''
 infile = StringIO(fileText)

 keyvalues = {}
 matrices  = {}
 for line in infile:
 fields = line.strip().split()
 if len(fields) == 2:
 keyvalues[fields[0]] = fields[1]
 lastkey = fields[0]
 elif fields:
 matrices.setdefault(lastkey, []).append(fields)

 ==
 Here is the sample output:

  from pprint import pprint as pp
  pp(keyvalues)
 {'key1': 'value1',
  'key2': 'value2',
  'key3': 'value3',
  'key4': 'value4',
  'key5': 'value5',
  'key6': 'value6',
  'key7': 'value7',
  'key8': 'value8'}
  pp(matrices)
 {'key4': [['spec11', 'spec12', 'spec13', 'spec14'],
   ['spec21', 'spec22', 'spec23', 'spec24'],
   ['spec31', 'spec32', 'spec33', 'spec34']],
  'key7': [['more11', 'more12', 'more13'], ['more21', 'more22',
 'more23']]}
 

Paddy, thanks, this looks even better.
Paul, pyparsing looks like an overkill, even the config parser module
is something that is too complex for me for such a simple task. The
text files are actually input files to a program and will never be
longer than 20-30 lines so Paddy's solution is perfectly fine. In any
case it's good to know that there exists a module called pyparsing :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Join strings - very simple Q.

2007-03-23 Thread Daniel Nogradi
  I was told in this NG that string is obsolet. I should use
  str methods.
 
  So, how do I join a list of strings delimited by a given
  char, let's say ','?
 
  Old way:
 
  l=['a','b','c']
  jl=string.join(l,',')
 
  New way?

 Dunno if it's the new way, but you can do: ''.join(l)

The OP wants the strings to be comma delimited:

jl=','.join(l)
-- 
http://mail.python.org/mailman/listinfo/python-list


On text processing

2007-03-23 Thread Daniel Nogradi
Hi list,

I'm in a process of rewriting a bash/awk/sed script -- that grew to
big -- in python. I can rewrite it in a simple line-by-line way but
that results in ugly python code and I'm sure there is a simple
pythonic way.

The bash script processed text files of the form:

###
key1value1
key2value2
key3value3

key4value4
spec11  spec12   spec13   spec14
spec21  spec22   spec23   spec24
spec31  spec32   spec33   spec34

key5value5
key6value6

key7value7
more11   more12   more13
more21   more22   more23

key8value8
###

I guess you get the point. If a line has two entries it is a key/value
pair which should end up in a dictionary. If a key/value pair is
followed by consequtive lines with more then two entries, it is a
matrix that should end up in a list of lists (matrix) that can be
identified by the key preceeding it. The empty line after the last
line of a matrix signifies that the matrix is finished and we are back
to a key/value situation. Note that a matrix is always preceeded by a
key/value pair so that it can really be identified by the key.

Any elegant solution for this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On text processing

2007-03-23 Thread Daniel Nogradi
 This is my first try:

 ddata = {}

 inside_matrix = False
 for row in file(data.txt):
 if row.strip():
 fields = row.split()
 if len(fields) == 2:
 inside_matrix = False
 ddata[fields[0]] = [fields[1]]
 lastkey = fields[0]
 else:
 if inside_matrix:
 ddata[lastkey][1].append(fields)
 else:
 ddata[lastkey].append([fields])
 inside_matrix = True

 # This gives some output for testing only:
 for k in sorted(ddata):
 print k, ddata[k]


 Input file data.txt:

 key1value1
 key2value2
 key3value3

 key4value4
 spec11  spec12   spec13   spec14
 spec21  spec22   spec23   spec24
 spec31  spec32   spec33   spec34

 key5value5
 key6value6

 key7value7
 more11   more12   more13
 more21   more22   more23

 key8value8


 The output:

 key1 ['value1']
 key2 ['value2']
 key3 ['value3']
 key4 ['value4', [['spec11', 'spec12', 'spec13', 'spec14'], ['spec21',
 'spec22', 'spec23', 'spec24'], ['spec31', 'spec32', 'spec33',
 'spec34']]]
 key5 ['value5']
 key6 ['value6']
 key7 ['value7', [['more11', 'more12', 'more13'], ['more21', 'more22',
 'more23']]]
 key8 ['value8']


 If there are many simple keys, then you can avoid creating a single
 element list for them, but then you have to tell apart the two cases
 on the base of the key (while now the presence of the second element
 is able  to tell apart the two situations). You can also use two
 different dicts to keep the two different kinds of data.

 Bye,
 bearophile

Thanks very much, it's indeed quite simple. I was lost in the
itertools documentation :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Documentation for str() could use some adjustment.

2007-03-19 Thread Daniel Nogradi
 The Python documentation for str says
 str([object]) :
  Return a string containing a nicely printable representation of an
 object.

 However, there's no mention of the fact that str of a Unicode string
 with non-ASCII characters will raise a conversion exception.  The
 documentation (and several Python books) seem to indicate that str will
 produce some printable representation for anything, not raise an
 exception.

 I know, it was proposed in PEP 349 to change str to return Unicode
 strings, and that's coming someday, along with all-Unicode Python,
 but meanwhile, the documentation should be clear about this.

Hi John, I'm not at all an expert around here but my understanding of
the workflow is that bug reports should be submitted to the tracker at
sourceforge. There is no guarantee that they will be noticed there but
the chances there are much higher than for a message on the mailing
list. I just mention this because I've seen your mysqld, urllib and
other potentially important bug reports here with no action taken but
maybe submitting them to sourceforge would attract some developers.
-- 
http://mail.python.org/mailman/listinfo/python-list


from maple to python + numpy/scipy

2007-03-19 Thread Daniel Nogradi
I'm just getting started with numpy/scipy and first would like to get
a view of what it can do and what it can't. The main idea is to move
from maple to python and the first thing that poped up is the fact
that maple is very convenient for both formal manipulations and exact
integer calculations. For instance if a matrix has integer entries and
the eigenvalues are integers maple can find these exactly.

Can numpy/scipy do this? Or the eigenvalues will always be floating
point numbers?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension help

2007-03-18 Thread Daniel Nogradi
 I need to process a really huge text file (4GB) and this is what i
 need to do. It takes for ever to complete this. I read some where that
 list comprehension can fast up things. Can you point out how to do
 it in this case?
 thanks a lot!


 f = open('file.txt','r')
 for line in f:
 db[line.split(' ')[0]] = line.split(' ')[-1]
 db.sync()

What is db here? Looks like a dictionary but that doesn't have a sync method.
If the file is 4GB are you sure you want to store the whole thing into
memory? In case yes and you want to store it in a list then you can
use list comprehension like this:

db = [ line.split(' ')[-1] for line in open('file.txt','r') ]

or

db = [ ( line.split(' ')[0], line.split(' ')[-1] ) for line in
open('file.txt','r') ]

depending on what exactly you want to store. But reading 4GB into
memory will be slow in any case. You can use the timeit module to find
out which method is fastest.

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension help

2007-03-18 Thread Daniel Nogradi
   I need to process a really huge text file (4GB) and this is what i
   list comprehension can fast up things. Can you point out how to do
   f = open('file.txt','r')
   for line in f:
   db[line.split(' ')[0]] = line.split(' ')[-1]
   db.sync()
 
  What is db here? Looks like a dictionary but that doesn't have a sync 
  method.

 db is a handle for Berkely db that i open with import bsddb

 import bsddb
 db=bsddb.hashopen('db_filename')

  If the file is 4GB are you sure you want to store the whole thing into
  memory?

 I dont want to load it in memory. Once I call the sync() function it
 get synced to the disk, and it is not loaded completely.

  use list comprehension like this:
  db = [ line.split(' ')[-1] for line in open('file.txt','r') ]
  or
  db = [ ( line.split(' ')[0], line.split(' ')[-1] ) for line in
  open('file.txt','r') ]
 
  depending on what exactly you want to store.

 line.split(' ')[0] is the key and line.split(' ')[-1] is the value.
 THat is what I want to store.
 Will the second line comprehension work in this case?

No, I don't think so. I gave that example because you wanted to use
list comprehension and I didn't know what db is but as the name says
it is for lists. Since the bsddb handle is not a list I'm afraid you
won't be able to use list comprehension.

This small thing will speed up your loop but since syncing is IO bound
it won't give you much (the timeit module will tell you how much you
save, if at all):

for line in f:
sp = line.split
db[sp(' ')[0]] = sp(' ')[-1]
db.sync( )

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list-like behaviour of etree.Element

2007-03-05 Thread Daniel Nogradi
  The etree.Element (or ElementTree.Element) supports a number of
  list-like methods: append, insert, remove. Any special reason why it
  doesn't support pop and extend (and maybe count)?
 
  Those methods would not be hard to add.  Perhaps, submit a feature
  request to Fredrik Lundh on SourceForge and see what he thinks there
  is merit in more closely emulating the list API.  Of the methods you
  listed, the case is probably strongest for extend().

 extend() will be in the next release:

 http://effbot.org/zone/elementtree-changes-13.htm

 (lxml.etree already has it, btw).

 not sure I see the point of pop() and count().  a successful feature request
 would need to include some really compelling use cases.

Great! I also first thought of extend because that would be really
useful, pop and count just came to mind because they exist for lists.
But if extend will be added that'll already make life easier,
pop/count is probably not that much needed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where I could find older python releases ?

2007-03-04 Thread Daniel Nogradi
 Sorry jumped the gun a little there. Is this what you are looking for?
 http://codespeak.net/download/py/py-0.9.0.zip

Probably not, the OP is looking for a python distribution, what you
are posting is a third party package *for* python and is actually a
part of the pypy project.
-- 
http://mail.python.org/mailman/listinfo/python-list


list-like behaviour of etree.Element

2007-03-04 Thread Daniel Nogradi
The etree.Element (or ElementTree.Element) supports a number of
list-like methods: append, insert, remove. Any special reason why it
doesn't support pop and extend (and maybe count)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing an interpreter for language similar to python!!

2007-03-02 Thread Daniel Nogradi
 I am new to python and working on a project that involves designing a
 new language. The grammar of the language is very much inspired from
 python as in is supports nearly all the statements and expressions
 that are supported by python. Since my project is in initial stage, so
 I think it would be appropriate if I clarify the following questions:

 1. Would it make sense if I parse the whole program from scratch and
 then construct the valid python strings back so that they can be
 executed using ''exec'' and ''eval'' commands?
 2. Recently, I came across PLY (Python-Lex-Yacc) module that can be
 used to implement interpreters. It seems quite friendly to work with.
 Is there any implementation of python interpreter using ply? Any such
 reference would be extermely helpful for me to continue.

 Any kind of suggestions/ comments would be highly appreciated.


You might want to look at the pypy project:

http://codespeak.net/pypy/dist/pypy/doc/news.html

A javascript interpreter has already been written using pypy:

http://codespeak.net/svn/user/santagada/javascript_interpreter_sop.txt
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: gmpy moving to code.google.com

2007-03-01 Thread Daniel Nogradi
  Could you please tell me, on that 64-bit build, what happens with:

   importgmpy, sys, operator
   sys.maxint
  ???
  gmpy.mpz(sys.maxint)
  ???
   operator.index(gmpy.mpz(sys.maxint))
  ???
   sys.maxint+1
  ???
  gmpy.mpz(sys.maxint+1)
  ???
   operator.index(gmpy.mpz(sys.maxint)+1)
  ???

  i.e., what are the values correspondiing to the ??? occurrences when
  you actually do that...?

 Here it goes (python 2.5 - 64bit):

  importgmpy, sys, operator
  sys.maxint
 9223372036854775807
 gmpy.mpz(sys.maxint)
 mpz(-1)
  operator.index(gmpy.mpz(sys.maxint))
 -1
  sys.maxint+1

 9223372036854775808Lgmpy.mpz(sys.maxint+1)

 mpz(9223372036854775808L) operator.index(gmpy.mpz(sys.maxint)+1)

 0

 I don't pretent to fully understand what's going on,
 butgmpy.mpz(sys.maxint)==gmpy.mpz(-1) is more than suspicious :)


[directing Alex's message back to the list]


Yes, clearly there is some 32-vs-64 bit assumption around.  When I
create an mpz from a Python int (a PyObject* i which passes Python's
int typecheck) I do that by calling mpz_from_c_long(PyInt_AsLong(i))
-- depending on what long means in C, I guess that might be the root
of the problem.  There might be similar problems in creating mpq and
mpf from Python ints  2**31-1 on 64-bit platforms, I guess.

I could try flailing around in the dark to fix it, but, without access
to a 64-bit Python platform, I don't really see any chance of me
fixing this.

If somebody can give me ssh access to such a platform, I'll be glad to
work to give it a try; of course, if anybody who does have access to
such a platform wants to send me patches or join the gmpy project,
that would also be great; failing either of these options, I don't see
much that I could do beyond pointing out in the docs that gmpy does
not correctly support 64-bits builds of Python, checking for them in
the unittests, etc.


Thanks,

Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Curious UnboundLocalError Behavior

2007-02-28 Thread Daniel Nogradi
 I'm probably fundamentally misunderstanding the way the interpreter
 works with regard to scope, but is this the intended behavior...


[]

 SOMEGLOBAL:
 Traceback (most recent call last):
   File unboundlocal.py, line 15, in ?
 foo()
   File unboundlocal.py, line 11, in foo
 print SOMEGLOBAL:,SOMEGLOBAL
 UnboundLocalError: local variable 'SOMEGLOBAL' referenced before assignment

[..]

 import os,sys

 SOMEGLOBAL=1

 def foo():
 dome=False
 if dome:
 SOMEGLOBAL = 0

 print globals()
 print SOMEGLOBAL:,SOMEGLOBAL

 print os.uname()
 print sys.version
 foo()



Try:

import os,sys

SOMEGLOBAL=1

def foo():
global SOMEGLOBAL
dome=False
if dome:
SOMEGLOBAL = 0

print globals()
print SOMEGLOBAL:,SOMEGLOBAL

print os.uname()
print sys.version
foo()

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gmpy moving to code.google.com

2007-02-28 Thread Daniel Nogradi
 Could you please tell me, on that 64-bit build, what happens with:

  import gmpy, sys, operator
  sys.maxint
 ???
  gmpy.mpz(sys.maxint)
 ???
  operator.index(gmpy.mpz(sys.maxint))
 ???
  sys.maxint+1
 ???
  gmpy.mpz(sys.maxint+1)
 ???
  operator.index(gmpy.mpz(sys.maxint)+1)
 ???

 i.e., what are the values correspondiing to the ??? occurrences when
 you actually do that...?

Here it goes (python 2.5 - 64bit):

 import gmpy, sys, operator
 sys.maxint
9223372036854775807
 gmpy.mpz(sys.maxint)
mpz(-1)
 operator.index(gmpy.mpz(sys.maxint))
-1
 sys.maxint+1
9223372036854775808L
 gmpy.mpz(sys.maxint+1)
mpz(9223372036854775808L)
 operator.index(gmpy.mpz(sys.maxint)+1)
0

I don't pretent to fully understand what's going on, but
gmpy.mpz(sys.maxint)==gmpy.mpz(-1) is more than suspicious :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gmpy moving to code.google.com

2007-02-27 Thread Daniel Nogradi
Hi Alex,

I did another test, this time with python 2.4 on suse and things are
worse than in the previous case (which was python 2.5 on fedora 3),
ouput of 'python gmp_test.py' follows:


Unit tests for gmpy 1.02 release candidate
on Python 2.4 (#1, Mar 22 2005, 21:42:42)
[GCC 3.3.5 20050117 (prerelease) (SUSE Linux)]
Testing gmpy 1.02 (GMP 4.1.3), default caching (20, 20, -2..11)
gmpy_test_cvr 270 tests, 0 failures
gmpy_test_rnd  26 tests, 0 failures
gmpy_test_mpf 155 tests, 0 failures
gmpy_test_mpq 264 tests, 0 failures
gmpy_test_mpz 376 tests, 0 failures
**
File /home/nogradi/tmp/gmpy/test/gmpy_test_dec.py, line ?, in
gmpy_test_dec.__test__.elemop
Failed example:
print f+d
Exception raised:
Traceback (most recent call last):
  File /usr/lib/python2.4/doctest.py, line 1243, in __run
compileflags, 1) in test.globs
  File doctest gmpy_test_dec.__test__.elemop[3], line 1, in ?
print f+d
  File /usr/lib/python2.4/decimal.py, line 906, in __add__
other = _convert_other(other)
  File /usr/lib/python2.4/decimal.py, line 2863, in _convert_other
raise TypeError, You can interact Decimal only with int, long
or Decimal data types.
TypeError: You can interact Decimal only with int, long or Decimal
data types.
**
File /home/nogradi/tmp/gmpy/test/gmpy_test_dec.py, line ?, in
gmpy_test_dec.__test__.elemop
Failed example:
print d+f
Exception raised:
Traceback (most recent call last):
  File /usr/lib/python2.4/doctest.py, line 1243, in __run
compileflags, 1) in test.globs
  File doctest gmpy_test_dec.__test__.elemop[4], line 1, in ?
print d+f
  File /usr/lib/python2.4/decimal.py, line 906, in __add__
other = _convert_other(other)
  File /usr/lib/python2.4/decimal.py, line 2863, in _convert_other
raise TypeError, You can interact Decimal only with int, long
or Decimal data types.
TypeError: You can interact Decimal only with int, long or Decimal
data types.
**
File /home/nogradi/tmp/gmpy/test/gmpy_test_dec.py, line ?, in
gmpy_test_dec.__test__.elemop
Failed example:
print q+d
Exception raised:
Traceback (most recent call last):
  File /usr/lib/python2.4/doctest.py, line 1243, in __run
compileflags, 1) in test.globs
  File doctest gmpy_test_dec.__test__.elemop[5], line 1, in ?
print q+d
  File /usr/lib/python2.4/decimal.py, line 906, in __add__
other = _convert_other(other)
  File /usr/lib/python2.4/decimal.py, line 2863, in _convert_other
raise TypeError, You can interact Decimal only with int, long
or Decimal data types.
TypeError: You can interact Decimal only with int, long or Decimal
data types.
**
File /home/nogradi/tmp/gmpy/test/gmpy_test_dec.py, line ?, in
gmpy_test_dec.__test__.elemop
Failed example:
print d+q
Exception raised:
Traceback (most recent call last):
  File /usr/lib/python2.4/doctest.py, line 1243, in __run
compileflags, 1) in test.globs
  File doctest gmpy_test_dec.__test__.elemop[6], line 1, in ?
print d+q
  File /usr/lib/python2.4/decimal.py, line 906, in __add__
other = _convert_other(other)
  File /usr/lib/python2.4/decimal.py, line 2863, in _convert_other
raise TypeError, You can interact Decimal only with int, long
or Decimal data types.
TypeError: You can interact Decimal only with int, long or Decimal
data types.
**
File /home/nogradi/tmp/gmpy/test/gmpy_test_dec.py, line ?, in
gmpy_test_dec.__test__.elemop
Failed example:
print z+d
Exception raised:
Traceback (most recent call last):
  File /usr/lib/python2.4/doctest.py, line 1243, in __run
compileflags, 1) in test.globs
  File doctest gmpy_test_dec.__test__.elemop[7], line 1, in ?
print z+d
  File /usr/lib/python2.4/decimal.py, line 906, in __add__
other = _convert_other(other)
  File /usr/lib/python2.4/decimal.py, line 2863, in _convert_other
raise TypeError, You can interact Decimal only with int, long
or Decimal data types.
TypeError: You can interact Decimal only with int, long or Decimal
data types.
**
File /home/nogradi/tmp/gmpy/test/gmpy_test_dec.py, line ?, in
gmpy_test_dec.__test__.elemop
Failed example:
print d+z
Exception raised:
Traceback (most recent call last):
  File /usr/lib/python2.4/doctest.py, line 1243, in __run
compileflags, 1) in test.globs
  File doctest gmpy_test_dec.__test__.elemop[8], line 1, in ?
print d+z
  File /usr/lib/python2.4/decimal.py, line 906, in __add__
other = 

Re: gmpy moving to code.google.com

2007-02-27 Thread Daniel Nogradi
  Hi Alex,
 
  I did another test, this time with python 2.4 on suse and things are
  worse than in the previous case (which was python 2.5 on fedora 3),
  ouput of 'python gmp_test.py' follows:

 Interesting!  gmpy interacts with decimal.Decimal by monkey-
 patching that class on the fly; clearly the monkey-patching isn't
 working with 2.4 on SuSE, so all the addition attempts are failing
 (all 6 of them).

 So the issue is finding out why this strategy is failing there, while
 succeeding on other Linux distros, Mac, and Windows.

 To that end, I have added a feature in the latest svn trunk (revision
 11) to set gmpy's own options.debug flag from an environment variable
 named GMPY_DEBUG at startup (if that environment variable is set).

 If you could please svn up and rebuild, then running with GMPY_DEBUG
 set in the environment should give something like:

 brain:~/gmpy alex$ GMPY_DEBUG=1 python -c 'import gmpy' 21 | tail -5
 mp_allocate( 4-8 )
 mp_allocate( 4-8 ) -0x60b8b0
 gmpy_module at 0x63390
 gmpy_module imported decimal OK
 gmpy_module tweaked decimal OK

 This is the expected behavior when module decimal is present, while,
 when it's absent, you should see something like:

 brain:~/gmpy alex$ GMPY_DEBUG=1 python2.3 -c 'import gmpy' 21 |
 tail -5
 Initing new not in zcache
 mp_allocate( 4-8 )
 mp_allocate( 4-8 ) -0x3017d0
 gmpy_module at 0x6de70
 gmpy_module could not import decimal

 In each case, what matters is the last line or two after gmpy_module
 at -- the rest of the copious debugging output is irrelevant here.

 Module decimal is expected to be present from 2.4 forward (though it
 could also be explicitly installed on 2.3).  However, from the test
 failures you report, it looks like SuSE's 2.4 does not have decimal
 available for importing when gmpy is starting up -- so I'd like to
 confirm that first.

 If it's confirmed, it will be interesting to discover how this
 happens (but that requires a SuSE installation, which I don't have)
 and secondarily what is gmpy to do about it -- maybe offer a warning
 on startup when module decimal is unexpectedly not importable but
 then skip the relevant unittests in that case?  (Note that the tests
 ARE already skipped if module decimal is not importable _at test
 time_ -- what's really weird is that apparently on SuSE decimal CAN
 be imported by the tests but CANNOT be imported earlier while gmpy is
 loading, which is truly puzzling).

 I'd appreciate reports about this behavior on as many Python/Linux
 installations as possible -- yours, of course (to check my guess that
 the problem is that decimal can't be imported while gmpy is loading),
 but also others' (to see how widespread the problem is, etc, etc).

 Thanks again for reporting this, and thanks in advance to anybody
 who'll lend a hand in tracking down this little strangeness!!!

Okay, here is a summary. The notation is:

platform version python version debug unittest

where debug will be either 'pass' or 'fail' if that particular
platform and python version passes or fails the GMPY_DEBUG=1
importing/tweaking test. Unittest will also be 'pass' or 'fail' if the
full unittesting passes or fails respectively.

Fedora 3 python 2.5passpass
Fedora 3 python 2.4passfail
Fedora 3 python 2.3.4 fail   pass
Suse 9.3 python 2.4passfail
Suse 10 python 2.4.1  passpass
Suse 10.2(64bit) python 2.5 passfail

The output from each test is zipped and you can grab it from here:
http://lorentz.leidenuniv.nl/~nogradi/gmpy_test.zip

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


[OT] python notation in new NVIDIA architecture

2007-02-26 Thread Daniel Nogradi
Something funny:

The new programming model of NVIDIA GPU's is called CUDA and I've
noticed that they use the same __special__ notation for certain things
as does python. For instance their modified C language has identifiers
such as __device__, __global__, __shared__, etc. Is it a coincidence?
Probably it is. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] python notation in new NVIDIA architecture

2007-02-26 Thread Daniel Nogradi
  Something funny:
 
  The new programming model of NVIDIA GPU's is called CUDA and I've
  noticed that they use the same __special__ notation for certain things
  as does python. For instance their modified C language has identifiers
  such as __device__, __global__, __shared__, etc. Is it a coincidence?
  Probably it is. :)

 Cuda is usually taken as short for barracuda, a fish. Fish have been
 known to slither under the right circumstances. Perhaps this is the link?

Wow! How is it that I didn't think about this before?! Thanks a million!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I don't quite understand this error...

2007-02-26 Thread Daniel Nogradi
 Thus far, everything works fine unless I'm trying the Deposit or Withdrawal
 functions. (I know they're different, but both give roughly the same error.)
 Whenever I attempt one of these functions I get the following error message:


 Exception in Tkinter callback
 Traceback (most recent call last):
   File C:\Python24\lib\lib-tk\Tkinter.py, line 1345, in __call__
 return self.func(*args)
   File C:\Python24\AEOpaypal.py, line 27, in Deposit
 user, passw, balance = accountlist[whichSelected()]
   File C:\Python24\AEOpaypal.py, line 11, in whichSelected
 return int(select.curselection()[0])
 IndexError: tuple index out of range

IndexError: tuple index out of range means that you are trying to
access an element of a tuple which does not exist. In your case
int(select.curselection()[0]) raises the exception so your tuple
select.curselection() doesn't have a 0th entry which means it's empty.

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gmpy moving to code.google.com

2007-02-26 Thread Daniel Nogradi
 If you're interested in gmpy (the Python wrapper of GMP, for
 unlimited-precision arithmetic, rationals, random number generation,
 number-theoretical functions, etc), please DO check out
 http://code.google.com/p/gmpy/ -- gmpy 1.02 is there (as far as I can
 tell) in a workable state.  Source on Subversion (and a prerelease
 zipfile too), downloadable binaries for MacOSX (download and read the
 README file first!) and Windows (for Python 2.4 and 2.5 only, built and
 minimally tested on a shaky Win2K+mingw -- on -- Parallels/MacOSX
 setup... I have no other Windows machine to check 'em out...!).

 Please help me check that the move-and-upgrade went OK -- download some
 or all of the pieces (including an svn checkout of the sources), build,
 install, test, try it out.  I will HEARTILY welcome feedback (mail
 [EMAIL PROTECTED]) telling me what worked and/or what didn't so I can
 finalize this release -- and hopefully move on to a future 1.03 (I won't
 aim to 1.03 until I'm convinced that 1.02 is OK...).


 Thanks in advance,

 Alex

Svn checkout, compilation and installation went okay but some tests
failed, this is the output of 'python test_gmpy.py':


Unit tests for gmpy 1.02 release candidate
on Python 2.5 (r25:51908, Nov  1 2006, 11:42:37)
[GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)]
Testing gmpy 1.02 (GMP 4.1.4), default caching (20, 20, -2..11)
gmpy_test_cvr 270 tests, 0 failures
gmpy_test_rnd  26 tests, 0 failures
gmpy_test_mpf 155 tests, 0 failures
gmpy_test_mpq 264 tests, 0 failures
**
File /home/nogradi/tmp/gmpy/test/gmpy_test_mpz.py, line ?, in
gmpy_test_mpz.__test__.number
Failed example:
_memsize()-_siz
Expected:
0
Got:
-4
**
1 items had failures:
   2 of 132 in gmpy_test_mpz.__test__.number
***Test Failed*** 2 failures.
gmpy_test_mpz 388 tests, 2 failures
**
1 items had failures:
   2 of 132 in gmpy_test_mpz.__test__.number
***Test Failed*** 2 failures.
gmpy_test_dec  16 tests, 0 failures
7 items had no tests:
gmpy_test_cvr._test
gmpy_test_dec._test
gmpy_test_mpf._test
gmpy_test_mpq._test
gmpy_test_mpz._memsize
gmpy_test_mpz._test
gmpy_test_rnd._test
30 items passed all tests:
   6 tests in gmpy_test_cvr
  12 tests in gmpy_test_cvr.__test__.misc_stuff
 252 tests in gmpy_test_cvr.__test__.user_errors
   1 tests in gmpy_test_dec
  15 tests in gmpy_test_dec.__test__.elemop
   1 tests in gmpy_test_mpf
  32 tests in gmpy_test_mpf.__test__.binio
  33 tests in gmpy_test_mpf.__test__.cmpr
  49 tests in gmpy_test_mpf.__test__.elemop
  34 tests in gmpy_test_mpf.__test__.format
   6 tests in gmpy_test_mpf.__test__.newdiv
   2 tests in gmpy_test_mpq
  26 tests in gmpy_test_mpq.__test__.binio
  62 tests in gmpy_test_mpq.__test__.cmpr
  66 tests in gmpy_test_mpq.__test__.elemop
  54 tests in gmpy_test_mpq.__test__.format
  12 tests in gmpy_test_mpq.__test__.newdiv
  18 tests in gmpy_test_mpq.__test__.power
  24 tests in gmpy_test_mpq.__test__.qdiv
   4 tests in gmpy_test_mpz
  34 tests in gmpy_test_mpz.__test__.binio
  62 tests in gmpy_test_mpz.__test__.bitops
  48 tests in gmpy_test_mpz.__test__.cmpr
  42 tests in gmpy_test_mpz.__test__.elemop
  36 tests in gmpy_test_mpz.__test__.format
  14 tests in gmpy_test_mpz.__test__.index
  12 tests in gmpy_test_mpz.__test__.newdiv
   4 tests in gmpy_test_mpz.factorize
   1 tests in gmpy_test_rnd
  25 tests in gmpy_test_rnd.__test__.rand
**
1 items had failures:
   2 of 132 in gmpy_test_mpz.__test__.number
1119 tests in 38 items.
1117 passed and 2 failed.
***Test Failed*** 2 failures.



HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help on Dict

2007-02-25 Thread Daniel Nogradi
 Can any body tell how Dict is implemented in python... plz tell what
 datastructure that uses

Please see

http://svn.python.org/view/python/trunk/Objects/dictnotes.txt?rev=53782view=markup

for general notes and

http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=53911view=markup

for the actual implementation.

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JIT (just-in-tme accelerator) for Python - exists or no?

2007-02-22 Thread Daniel Nogradi
 Or is any progress going on now?

 The JIT in MATLAB or Java seems to be very effective.


This document describes the JIT situation in pypy:

http://codespeak.net/pypy/dist/pypy/doc/jit.txt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: conver string to dictionary

2007-02-18 Thread Daniel Nogradi
   I want to convert string to dictionary .what is the best solution for this?
   for example string is like this:


 '{SalutationID:[primarykey,8388607,0,None],CompanyID:[0,8388607,0,index],
  SalutationName:[,255,0,None],isDefault:[tinyint,1,1,None]}'

   and I want to convert this string to this dictionary:


 {SalutationID:[primarykey,8388607,0,None],CompanyID:[0,8388607,0,index],
  SalutationName:[,255,0,None],isDefault:[tinyint,1,1,None]}

   please help me what is the best solution(faster solution) for this?


If you have simplejson  ( http://cheeseshop.python.org/pypi/simplejson
) installed you can do
mydict = simplejson.loads( mystring )
but in this case all occurances of 'None' in your string should be 'null'.

Or if you absolutely trust the string to contain nothing dangerous:
exec( 'mydict = %s' % mystring )

HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >