Re: How do I get the constructor signature for built-in types?

2012-06-05 Thread Ian Kelly
On Mon, Jun 4, 2012 at 11:19 PM, Steven D'Aprano
 wrote:
> How do I programmatically get the argument spec of built-in types'
> __init__ or __new__ methods?

I don't think that you can. Methods implemented in C don't really even
have established argument specs.  They just take tuples and dicts and
use the PyArg_Parse* family of functions to unpack them.  So
effectively, all built-in methods have the argspec (self, *args,
**keywords)

Cheers,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list


stop thread from outside 'run'

2012-06-05 Thread Prashant
Hi,

I am using tornado web socket server to communicate between python(server) and 
browser(client). To mimic the behavior of sending data to client and get 
results back, I am using threaded approach:

class JobThread(threading.Thread):
""
def __init__(self, target):
""
super(JobThread, self).__init__()
self.target = target
self.res = None
self.stoprequest = threading.Event()
self.start()
self.join()
# Execution stops here and wait
return self.result()

def run(self):
""" Start this thread """
self.target()
while not self.stoprequest.isSet():
print "running..."

def result(self):
""
return self.res

def kill(self, result):
""" Kill this thread """
self.res = result
self.stoprequest.set()

def ReceiveData(message):
""
global t
print str(message)
t.kill(message)

def SendData(data_string):
""
sendMessageWS(data_string)

result = JobThread(partial(SendData, data_string))

As soon as jobThread instance starts it sends data to websocket and wait for 
client to response. Client is sending back results but 'ReceiveData' is not 
getting called because of infinite loop in 'run' method. The only way you can 
stop the thread is from outside when "ReceiveData" executes and kill the 
threaded instance 't'. 

Any pointers?
-- 
http://mail.python.org/mailman/listinfo/python-list


Metaclass of a metaclass

2012-06-05 Thread Steven D'Aprano
I was playing around with metaclasses and I wondered what would happen if 
the metaclass itself had a metaclass. Sort of a metametaclass.

Apparently it gives an error. Can anyone explain why this does not work?

# Python 3.2



>>> class MyType(type):  # A metaclass...
... def __repr__(self):
... s = super().__repr__()
... return s.replace('class', 'metaclass')
... 
>>> class Meta(metaclass=MyType):  # ... of a metaclass.
... pass
... 
>>> Meta

>>> 
>>> isinstance(Meta, type)
True
>>> 
>>> 
>>> class MyClass(metaclass=Meta):  # And now try to use it.
... pass
... 
Traceback (most recent call last):
  File "", line 1, in 
TypeError: object.__new__() takes no parameters



What am I doing wrong?


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


Re: Metaclass of a metaclass

2012-06-05 Thread Peter Otten
Steven D'Aprano wrote:

> I was playing around with metaclasses and I wondered what would happen if
> the metaclass itself had a metaclass. Sort of a metametaclass.
> 
> Apparently it gives an error. Can anyone explain why this does not work?
> 
> # Python 3.2
> 
> 
> 
 class MyType(type):  # A metaclass...
> ... def __repr__(self):
> ... s = super().__repr__()
> ... return s.replace('class', 'metaclass')
> ...
 class Meta(metaclass=MyType):  # ... of a metaclass.
> ... pass
> ...
 Meta
> 
 
 isinstance(Meta, type)
> True

I think you want isinstance(Meta(), type), and this returns False.

 class MyClass(metaclass=Meta):  # And now try to use it.
> ... pass
> ...
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: object.__new__() takes no parameters
> 
> 
> 
> What am I doing wrong?

class A(metaclass=M):
pass

is equivalent to

A = M(name, bases, classdict)

and as the error message suggests B needs a compatible signature.


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


Re: Namespace hack

2012-06-05 Thread Daniel Fetchinson
>> Funny, you got to the last line of "import this" but apparently
>> skipped the second line:
>>
>> Explicit is better than implicit.
>>
>> And you didn't even post your message on April 1 so no, I can't laugh
>> even though I'd like to.
>
> Can you be less condescending?

Of course! :)

Anyway, the point I was trying to make is that Steve's example is
kinda cool but only as a funny exercise and not something for real
life. Let's toy with python kinda thing, which is always welcome but
with a big fat asterisk saying "don't try this at home kids".

Cheers,
Daniel



-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get the constructor signature for built-in types?

2012-06-05 Thread Terry Reedy

On 6/5/2012 1:19 AM, Steven D'Aprano wrote:

The inspect.getargspec and getfullargspec functions allow you to extract
the function call signature for Python functions and methods. This allows
you to work out the constructor signature for pure-Python classes, by
calling inspect.getargspec on the __init__ or __new__ method.

...


So far so good. But if the __init__ method is inherited directly from a
built-in, getargspec fails:



How do I programmatically get the argument spec of built-in types'
__init__ or __new__ methods?


Idle tooltips rely on doc strings for builtins. (And by the way, thanks 
for the example, as it might crash Idle even after my current patch. I 
will have to check. See http://bugs.python.org/issue12510 if interested.)


--
Terry Jan Reedy

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


Twisted 12.1.0 released

2012-06-05 Thread Thomas Hervé
On behalf of Twisted Matrix Laboratories, I am pleased to announce the
release of Twisted 12.1.

107 tickets are closed by this release, with the following highlights:

 * The revival of the kqueue reactor for BSD platforms.

 * epoll is now the default reactor under Linux after a fix to handle
files on stdin/stdout.

 * New reactors supporting GTK3 and GObject-Introspection.

 * Several enhancements regarding file descriptors passing: systemd
support for servers, ability to send and receive file descriptors for
IReactorUNIX and an AMP argument using that feature.

 * Support for IPv6 literals in connectTCP.

 * Persistent connections support for the new HTTP client.

This is the last Twisted release supporting Python 2.5.

For more information, see the NEWS file here:

 http://twistedmatrix.com/Releases/Twisted/12.1/NEWS.txt


Download it now from:

 http://pypi.python.org/packages/source/T/Twisted/Twisted-12.1.0.tar.bz2 or

http://pypi.python.org/packages/2.5/T/Twisted/Twisted-12.1.0.win32-py2.5.msi
or

http://pypi.python.org/packages/2.6/T/Twisted/Twisted-12.1.0.win32-py2.6.msi
or

http://pypi.python.org/packages/2.7/T/Twisted/Twisted-12.1.0.win32-py2.7.msi


Thanks to the supporters of Twisted via the Software Freedom Conservancy
and to the many contributors for this release.

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


Re: Metaclass of a metaclass

2012-06-05 Thread Ian Kelly
On Tue, Jun 5, 2012 at 2:48 AM, Steven D'Aprano
 wrote:
> I was playing around with metaclasses and I wondered what would happen if
> the metaclass itself had a metaclass. Sort of a metametaclass.
>
> Apparently it gives an error. Can anyone explain why this does not work?

In your example, Meta is not actually a metaclass, as it inherits from
object, not type.  Here's an example that works:

>>> class MetaMeta(type): pass
...
>>> class Meta(type, metaclass=MetaMeta): pass
...
>>> class MyClass(metaclass=Meta): pass
...

Anyway, metaclasses of metaclasses is not that unusual, as type is
already its own metaclass.

Cheers,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ./configure

2012-06-05 Thread Janet Heath
On Jun 3, 10:01 pm, Janet Heath 
wrote:
> On Jun 3, 6:31 pm, Steven D'Aprano 
>
>
>
>
>
>
>
>
> +comp.lang.pyt...@pearwood.info> wrote:
> > On Sun, 03 Jun 2012 15:01:07 -0700, Janet Heath wrote:
> > > Thanks Alain.  I should have a compiler on my Mac OS X Lion.  I am
> > > thinking that it isn't set in my $PATH variable.  I don't know where the
> > > $PATH is set at.  I will check to see if their is a binary.
>
> > At the command line, run:
>
> > echo $PATH
>
> > to see the path.
>
> > I'm not sure where OS X sets the PATH, but Linux systems normally set
> > them in /etc/profile. User-customisations should go in a shell rc file,
> > e.g. if you are using bash, edit ~/.bashrc.
>
> > To add additional paths to the PATH:
>
> > export $PATH=$PATH:/some/directory:/another/directory
>
> > To replace the system path completely:
>
> > export $PATH=/some/directory:/another/directory
>
> > --
> > Steven
>
> Thanks Steven!

Thanks Irmen!
-- 
http://mail.python.org/mailman/listinfo/python-list


fputs

2012-06-05 Thread hassan
Dear ALL , 

what is the equivalent to the php fputs in python 


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


what gui designer is everyone using

2012-06-05 Thread Mark R Rivet
I want a gui designer that writes the gui code for me. I don't want to
write gui code. what is the gui designer that is most popular?
I tried boa-constructor, and it works, but I am concerned about how
dated it seems to be with no updates in over six years.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what gui designer is everyone using

2012-06-05 Thread matteo.bosc...@boscolini.eu
you have the qt designer with eric is nice and easy to use for the qt ..


Da: python-list-bounces+matteo.boscolo=boscolini...@python.org
A: python-list@python.org
Cc: 
Data: Tue, 05 Jun 2012 10:10:17 -0400
Oggetto: what gui designer is everyone using

> I want a gui designer that writes the gui code for me. I don't want to
> write gui code. what is the gui designer that is most popular?
> I tried boa-constructor, and it works, but I am concerned about how
> dated it seems to be with no updates in over six years.
> -- 
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what gui designer is everyone using

2012-06-05 Thread becky_lewis
I'm afraid that in my experience, doing things by hand has always
ended up being quicker and simpler than relying on a GUI designer when
it comes to building python GUI apps. That said, I've not tried any
for the past few years so there may be a killer app out there that
I've not tried :) But even then, it's likely that you'll still have to
get your hands dirty in the code at some point.

Also, it would help a little if you'd state which toolkit you were
using (I'm assuming wxPython since you mention boa-constructor).


On Jun 5, 3:10 pm, Mark R Rivet  wrote:
> I want a gui designer that writes the gui code for me. I don't want to
> write gui code. what is the gui designer that is most popular?
> I tried boa-constructor, and it works, but I am concerned about how
> dated it seems to be with no updates in over six years.

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


Re: what gui designer is everyone using

2012-06-05 Thread rdsteph
On Jun 5, 7:10 am, Mark R Rivet  wrote:
> I want a gui designer that writes the gui code for me. I don't want to
> write gui code. what is the gui designer that is most popular?
> I tried boa-constructor, and it works, but I am concerned about how
> dated it seems to be with no updates in over six years.

No one size fits all, and many Pythonistas prefer to write GUI code by
hand anyway. However, I like PythonCard. Try it, you might like it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what gui designer is everyone using

2012-06-05 Thread parkerdg
On Tuesday, June 5, 2012 10:10:17 AM UTC-4, Manatee wrote:
> I want a gui designer that writes the gui code for me. I don't want to
> write gui code. what is the gui designer that is most popular?
> I tried boa-constructor, and it works, but I am concerned about how
> dated it seems to be with no updates in over six years.



On Tuesday, June 5, 2012 10:10:17 AM UTC-4, Manatee wrote:
> I want a gui designer that writes the gui code for me. I don't want to
> write gui code. what is the gui designer that is most popular?
> I tried boa-constructor, and it works, but I am concerned about how
> dated it seems to be with no updates in over six years.



On Tuesday, June 5, 2012 10:10:17 AM UTC-4, Manatee wrote:
> I want a gui designer that writes the gui code for me. I don't want to
> write gui code. what is the gui designer that is most popular?
> I tried boa-constructor, and it works, but I am concerned about how
> dated it seems to be with no updates in over six years.

I've used XRCed with wxpython in the past. XRCed is bundled with the wxPython 
installation. It was very easy to layout the GUI objects and setup the generic 
event bindings. 

Recently I've been playing around with using PyQt and QtDesigner because I keep 
seeing it highly recommened. The capabilities and process seem very similar to 
using XRCed to me.

These are simply GUI designers not IDE's. The basic process for using both is:
* Layout the GUI objects, define generic event bindings (wx) or signals/slots 
(Qt). 
* Save the GUI layout XML.
* Auto-generate a generic Python module that defines the GUI object based on 
the XML. 
* Import the and inherit from the generic Python GUI. Override the GUI class 
and methods as needed. 
* Write a script or a main function that instantiates the GUI and starts the 
event loop. 

I'm biased toward wxPython and XRCed mostly because I've had more experience 
with it and the documentation seems easier to follow.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what gui designer is everyone using

2012-06-05 Thread Vincent Vande Vyvre
On 05/06/12 16:10, Mark R Rivet wrote:
> I want a gui designer that writes the gui code for me. I don't want to
> write gui code. what is the gui designer that is most popular?
> I tried boa-constructor, and it works, but I am concerned about how
> dated it seems to be with no updates in over six years.
Try Qt

http://qt-project.org/doc/qt-4.8/designer-manual.html

-- 
Vincent V.V.
Oqapy  . Qarte+7
 . PaQager 

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


Re: Metaclass of a metaclass

2012-06-05 Thread bruno.desthuilli...@gmail.com
On Jun 5, 10:48 am, Steven D'Aprano  wrote:
> Apparently it gives an error. Can anyone explain why this does not work?
>
> # Python 3.2
>
> >>> class MyType(type):  # A metaclass...
>
> ...     def __repr__(self):
> ...             s = super().__repr__()
> ...             return s.replace('class', 'metaclass')
>
> >>> class Meta(metaclass=MyType):  # ... of a metaclass.
>
> ...     pass

(...)

> >>> class MyClass(metaclass=Meta):  # And now try to use it.
>
> ...     pass
> ...
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: object.__new__() takes no parameters
>
> What am I doing wrong?

Meta inherit from object, but being used as a metaclass, Meta.__new__
is called with name, bases, dict etc as arguments.

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


Re: fputs

2012-06-05 Thread Jugurtha Hadjar

On 06/05/2012 02:54 PM, hassan wrote:

Dear ALL ,

what is the equivalent to the php fputs in python


regards,


Hello,

Have you tried something like this (I'll be passing the filename as an 
argument):



from sys import argv

script, dest_file = argv


data_to_write = raw_input()

output = open(dest_file, 'w')

output.write(data_to_write)



You can execute it this way:

python  

e.g:

python script.py data.txt




--
~Jugurtha Hadjar,
--
http://mail.python.org/mailman/listinfo/python-list


Re: fputs

2012-06-05 Thread Ulrich Eckhardt
Am 05.06.2012 15:54, schrieb hassan:
> what is the equivalent to the php fputs in python 

If that fputs() is the same as C's fputs(), then write() is pretty
similar. Check the documentation for files, you will surely find the
equivalent.


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


Re: fputs

2012-06-05 Thread Rhodri James
On Tue, 05 Jun 2012 14:54:54 +0100, hassan   
wrote:



what is the equivalent to the php fputs in python


The write() method of the file object.  Though if you're
asking the question like that, you need to read this:

http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files

...and stop trying to think in terms of PHP.  While you
can write PHP in any language (I know people who still
write FORTRAN, whatever language they might be using),
you'll find that getting into the right mindset for
whatever language you are using works a lot better.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Available candidate for Oracle DBA

2012-06-05 Thread deepak tekwissen
Hi,

Hope you are doing good,,

Skill SetCurrent-location
RelocationAvailability

oracal DBAtennessee
yes  immediately


As per your requirement for Oracle DBA position, I’m forwarding you
one of my consultant’s resume. Please find the attachment and revert
back to me.
Let me know who is the client and whether he is your direct client or
not…

Have a great day ahead…
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stop thread from outside 'run'

2012-06-05 Thread MRAB

On 05/06/2012 09:11, Prashant wrote:

Hi,

I am using tornado web socket server to communicate between python(server) and 
browser(client). To mimic the behavior of sending data to client and get 
results back, I am using threaded approach:

class JobThread(threading.Thread):
 ""
 def __init__(self, target):
 ""
 super(JobThread, self).__init__()
 self.target = target
 self.res = None
 self.stoprequest = threading.Event()
 self.start()
 self.join()
 # Execution stops here and wait
 return self.result()

 def run(self):
 """ Start this thread """
 self.target()
 while not self.stoprequest.isSet():
 print "running..."

 def result(self):
 ""
 return self.res

 def kill(self, result):
 """ Kill this thread """
 self.res = result
 self.stoprequest.set()

def ReceiveData(message):
 ""
 global t
 print str(message)
 t.kill(message)

def SendData(data_string):
 ""
 sendMessageWS(data_string)

result = JobThread(partial(SendData, data_string))


JobThread is a class, so a statement of the form:

result = JobThread(...)

will simply create an instance of the JobThread class and then bind it
to the name "result".

The __init__  method is called to initialise the instance; any value
returned the method will be discarded.


As soon as jobThread instance starts it sends data to websocket and wait for client to 
response. Client is sending back results but 'ReceiveData' is not getting called because 
of infinite loop in 'run' method. The only way you can stop the thread is from outside 
when "ReceiveData" executes and kill the threaded instance 't'.

Any pointers?


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


Re: what gui designer is everyone using

2012-06-05 Thread Den
On Jun 5, 7:10 am, Mark R Rivet  wrote:
> I want a gui designer that writes the gui code for me. I don't want to
> write gui code. what is the gui designer that is most popular?
> I tried boa-constructor, and it works, but I am concerned about how
> dated it seems to be with no updates in over six years.

I use wxFormBuilder.  It seems to be most up-to-date and is as easy to
use as any others.  It also covers AUI GUIs.  It produces the class,
but you have to do a little bit of programming to actually see the
GUI.

I used wx-glade for a while.  It was easy to use, and produced ready-
to-run GUIs.  But it's old and not well kept up.  There's some new
work being done on it but it seems to be mostly housekeeping work -
how to best package it, etc.

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


English version for Mémento Python 3 (draft, readers needed)

2012-06-05 Thread Laurent Pointal
Hello,

I started a first translation of my document originally in french. Could 
some fluent english people read it and indicate errors or bad english 
expressions.

http://perso.limsi.fr/pointal/python:memento

Thanks.
A+
Laurent.

-- 
Laurent POINTAL - laurent.poin...@laposte.net

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


Has theHas Python community got Alan Saalfeld et al's algorithm and source code implementation

2012-06-05 Thread David Shi
Dear Python community friends,

I wonder whether there is such a Python implementation available.


Alan Saalfeld et al's algorithm and source codes.

http://books.google.ie/books/about/A_Modified_Douglas_Peucker_Simplificatio.html?id=gbQjywAACAAJ&redir_esc=y

In Zhiyuan Zhao and Alan Saafeld's paper, LINEAR-TIME SLEEVE-FITTING POLYLINE
SIMPLIFICATION ALGORITHMS
Zhiyuan Zhao, Alan Saalfeld

They mentioned "
The results of those
experiments and more information on the algorithms themselves, including
complete working code, are available to the interested reader at the World Wide
Web site http://ra.cfm.ohio-state.edu/grad/zhao/algorithms/linesimp.html.";

However, this site is no longer alive.

If anyone knows, please let me know.   davidg...@yahoo.co.uk

Regards.

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


Re: English version for Mémento Python 3 (draft, readers needed)

2012-06-05 Thread Paul Rubin
Laurent Pointal  writes:
> I started a first translation of my document originally in french. Could 
> some fluent english people read it and indicate errors or bad english 
> expressions.
>
> http://perso.limsi.fr/pointal/python:memento

It looks nice.  It took me a minute to find the English version:

  http://perso.limsi.fr/pointal/_media/python:cours:mementopython3-english.pdf

A few minor things:

1) We would usually call this a "reference card" rather than "memento"

2) In the dictionary example, 
   {"clé":"valeur"} =>  {"key":"value"}
   {1:"un",3:"trois",2:"deux",3.14:""} => {1:"one", etc. }

3) "bloc" in a few places should be "block"

4) On side 2, the part about writing files is still mostly in French

There are a few other things like that, and I'll try to look more
carefully tonight, I can't spend more time on it right now.

Thanks for writing it and sharing it.

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


Need a Python Developer in Mountain View,CA

2012-06-05 Thread o2kcompliant
Hi Guys,

I have a need for a Python Developer in Mountain View,CA.  Here are the 
requirements:

Solid foundation in computer science with strong competencies in data 
structures, algorithms and software design with proficiency in object-oriented 
design principles and extensive experience in Python  Java, Ruby, Perl, Groovy 
or Objective-C. . 2+ yrs professional MySQL experience. . Ability to work 
end-to-end on all aspects of MVC including UI work. . Experience with Flask, 
Jinja, Bootstrap, or Solr a plus. . Comfortable with agile dev cycle - we are 
using advanced scrum methods. . Broad Internet understanding: TCP/IP 
programming, basics of how HTTP and other major Internet protocols really work. 
. Experience with web application servers (Tomcat, Jetty, WebLogic, etc) and 
build and scm systems (ant, gradle, gmake, svn, git, perforce, etc.)

Please feel free to contact me if you are interested or have any questions.  
Thanks!

Asad Bawa | Account Executive
E: a...@midcom.com 
M: 714.642.3437 | D : 714.507.3717 | Tel: 800.737.1632 ext. 3717| F: 
714.459.7055
MIDCOM Corporation 3995 E. La Palma Ave., Anaheim, CA 92807

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


Re: English version for Mémento Python 3 (draft, readers needed)

2012-06-05 Thread MRAB

On 05/06/2012 18:32, Laurent Pointal wrote:

Hello,

I started a first translation of my document originally in french. Could
some fluent english people read it and indicate errors or bad english
expressions.

http://perso.limsi.fr/pointal/python:memento


In addition to what Paul wrote:

"mot" => "word"

min/MAJ case discrimination => case-sensitive

Identifiers no longer restricted to ASCII range. Even π is permitted.

litteral => literal

see verso => see reverse

logial => logical

Indexation des séquences => Indexing of sequences

exemple => example

nombres flottants => floating-point numbers

valeurs approchées => (not sure)

Opérators => Operators

remain => remainder

care to inifinite loops => beware of infinite loops (possibly)

cpt => cnt (possibly)

"trouvé" => "found"

modif => ?

littéral => literal

always return => always returns

recto => obverse ("obverse" is the "correct" word, although "front" 
might be clearer for those who don't know what "obverse" means!)


reversed copy => reverse iterator (note that it's an _iterator_)

défault => default

parametrs => parameters

"coucou" => "cuckoo"

fichier texte → lecture / écriture de chaînes uniquement, convertir 
de/vers le type désiré => text file → reads/writes strings (?)


ne pas oublier de refermer le fichier après son utilisation =>  don't 
forget to close the file after use


très courant : boucle itérative de lecture des lignes d'un fichier texte 
=> very common : iterative loop reading lines from a text file


ligne => line

bloc traitement de la ligne => block processing line

directives de formatage => format directives

valeurs à formater => Values to format

Paramètre de conversion => Conversion parameter

chaîne d'affichage => display string

chaîne de représentation => string representation (or "representation 
string"?)


apparition order by default => in order of appearance by default (?)

espace => space

ou => or

flot => float

pourcent => percent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help needed with nested parsing of file into objects

2012-06-05 Thread Eelco
> thank you both for your replies. Unfortunately it is a pre-existing
> file format imposed by an external system that I can't
> change. Thank you for the code snippet.

Hi Richard,

Despite the fact that it is a preexisting format, it is very close
indeed to valid YAML code.

Writing your own whitespace-aware parser can be a bit of a pain, but
since YAML does this for you, I would argue the cleanest solution
would be to bootstrap that functionality, rather than roll your own
solution, or to resort to hard to maintain regex voodoo.

Here is my solution. As a bonus, it directly constructs a custom
object hierarchy (obviously you would want to expand on this, but the
essentials are there). One caveat: at the moment, the conversion to
YAML relies on the appparent convention that instances never directly
contain other instances, and lists never directly contain lists. This
means all instances are list entries and get a '-' appended, and this
just works. If this is not a general rule, youd have to keep track of
an enclosing scope stack an emit dashes based on that. Anyway, the
idea is there, and I believe it to be one worth looking at.


import yaml

class A(yaml.YAMLObject):
yaml_tag = u'!A'
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
return 'A' + str(self.__dict__)

class B(yaml.YAMLObject):
yaml_tag = u'!B'
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
return 'B' + str(self.__dict__)

class C(yaml.YAMLObject):
yaml_tag = u'!C'
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
return 'C' + str(self.__dict__)

class TestArray(yaml.YAMLObject):
yaml_tag = u'!TestArray'
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
return 'TestArray' + str(self.__dict__)

class myList(yaml.YAMLObject):
yaml_tag = u'!myList'
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
return 'myList' + str(self.__dict__)


data = \
"""
An instance of TestArray
 a=a
 b=b
 c=c
 List of 2 A elements:
  Instance of A element
   a=1
   b=2
   c=3
  Instance of A element
   d=1
   e=2
   f=3
 List of 1 B elements
  Instance of B element
   a=1
   b=2
   c=3
   List of 2 C elements
Instance of C element
 a=1
 b=2
 c=3
Instance of C element
 a=1
 b=2
 c=3
An instance of TestArray
 a=1
 b=2
 c=3
""".strip()

#remove trailing whitespace and seemingly erronous colon in line 5
lines = ['  '+line.rstrip().rstrip(':') for line in data.split('\n')]


def transform(lines):
"""transform text line by line"""
for line in lines:
#regular mapping lines
if line.find('=') > 0:
yield line.replace('=', ': ')
#instance lines
p = line.find('nstance of')
if p > 0:
s = p + 11
e = line[s:].find(' ')
if e == -1: e = len(line[s:])
tag = line[s:s+e]
whitespace= line.partition(line.lstrip())[0]
yield whitespace[:-2]+' -'+ ' !'+tag
#list lines
p = line.find('List of')
if p > 0:
whitespace= line.partition(line.lstrip())[0]
yield whitespace[:-2]+'  '+ 'myList:'

##transformed = (transform( lines))
##for i,t in enumerate(transformed):
##print '{:>3}{}'.format(i,t)

transformed = '\n'.join(transform( lines))
print transformed

res = yaml.load(transformed)
print res
print yaml.dump(res)

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


Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 4, 3:20 pm, richard  wrote:
> On Jun 4, 3:14 pm, Alain Ketterlin 
> wrote:
>
>
>
>
>
>
>
>
>
> > richard  writes:
> > > Hi guys i am having a bit of dificulty finding the best approach /
> > > solution to parsing a file into a list of objects / nested objects any
> > > help would be greatly appreciated.
>
> > > #file format to parse .txt
> > > [code]
> > > An instance of TestArray
> > >  a=a
> > >  b=b
> > >  c=c
> > >  List of 2 A elements:
> > >   Instance of A element
>
> > [...]
>
> > Below is a piece of code that seems to work on your data. It builds a
> > raw tree, i leave it to you to adapt and built the objects you want. The
> > assumption is that the number of leading blanks faithfully denotes
> > depth.
>
> > As noted in another message, you're probably better off using an
> > existing syntax (json, python literals, yaml, xml, ...)
>
> > -- Alain.
>
> > #!/usr/bin/env python
>
> > import sys
> > import re
>
> > RE = re.compile("( *)(.*)")
> > stack = [("-",[])] # tree nodes are: (head,[children])
> > for line in sys.stdin:
> >     matches = RE.match(line)
> >     if len(matches.group(2)) > 0:
> >         depth = 1 + len(matches.group(1))
> >         while len(stack) > depth:
> >             stack[-2][1].append(stack[-1])
> >             del stack[-1]
> >             pass
> >         stack.append( (matches.group(2),[]) )
> >         pass
> >     pass
> > while len(stack) > 1:
> >     stack[-2][1].append(stack[-1])
> >     del stack[-1]
> >     pass
>
> > print(stack)
>
> thank you both for your replies. Unfortunately it is a pre-existing
> file format imposed by an external system that I can't
> change. Thank you for the code snippet.

Hi guys still struggling to get the code that was posted to me on this
forum to work in my favour and get the output in the format shown
above. This is what I have so far. Any help will be greatly
apprectiated.

output trying to achieve
parsed = [
{
  "a":"a",
  "b":"b",
  "c":"c",
  "A_elements":[
  {
"a":1,
"b":2,
"c":3
  },
  {
 "a":1,
 "b":2,
 "c":3
  }
   ],
  "B_elements":[
  {
"a":1,
"b":2,
"c":3,
"C_elements":[
 {
 "a":1,
 "b":2,
 "c":3
  },
  {
  "a":1,
  "b":2,
  "c":3
  }
 ]
  }
   ]
},

{
  "a":"1",
  "b":"2",
  "c":"3",
}

]

file format unchangeable

An instance of TestArray
 a=a
 b=b
 c=c
 List of 2 A elements:
  Instance of A element
   a=1
   b=2
   c=3
  Instance of A element
   d=1
   e=2
   f=3
 List of 1 B elements
  Instance of B element
   a=1
   b=2
   c=3
   List of 2 C elements
Instance of C element
 a=1
 b=2
 c=3
Instance of C element
 a=1
 b=2
 c=3

An instance of TestArray
 a=1
 b=2
 c=3

def test_parser(filename):
class Stanza:
def __init__(self, values):
for attr, val in values:
setattr(self, attr, val)

def build(couple):
if "=" in couple[0]:
attr, val = couple[0].split("=")
return attr,val
elif "Instance of" in couple[0]:
match = re.search("Instance of (.+) element", couple[0])
return ("attr_%s" % match.group(1),Stanza(couple[1]))
elif "List of" in couple[0]:
match = re.search("List of \d (.+) elements", couple[0])
return ("%s_elements" % match.group(1),couple[1])

fo = open(filename, "r")
RE = re.compile("( *)(.*)")
stack = [("-",[])]
for line in fo:
matches = RE.match(line)
if len(matches.group(2)) > 0:
depth = 1 + len(matches.group(1))
while len(stack) > depth:
stack[-2][1].append(build(stack[-1]))
del stack[-1]
stack.append( (matches.group(2),[]) )
while len(stack) > 1:
stack[-2][1].append(stack[-1])
del stack[-1]
return stack

stanzas = test_parser("test.txt")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English version for Mémento Python 3 (draft, readers needed)

2012-06-05 Thread Laurent Pointal
Paul Rubin wrote:

> Laurent Pointal  writes:
>> I started a first translation of my document originally in french. Could
>> some fluent english people read it and indicate errors or bad english
>> expressions.
>>
>> http://perso.limsi.fr/pointal/python:memento
> 
> It looks nice.  It took me a minute to find the English version:
> 
>   http://perso.limsi.fr/pointal/_media/python:cours:mementopython3-
english.pdf
> 
> A few minor things:
> 
> 1) We would usually call this a "reference card" rather than "memento"
> 
> 2) In the dictionary example,
>{"clé":"valeur"} =>  {"key":"value"}
>{1:"un",3:"trois",2:"deux",3.14:""} => {1:"one", etc. }
> 
> 3) "bloc" in a few places should be "block"
> 
> 4) On side 2, the part about writing files is still mostly in French
> 
> There are a few other things like that, and I'll try to look more
> carefully tonight, I can't spend more time on it right now.
> 
> Thanks for writing it and sharing it.
> 
> --Paul

Thanks,

I updated the document into 1.0.5a (and fix some other errors).

A+
Laurent.

-- 
Laurent POINTAL - laurent.poin...@laposte.net

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


Re: English version for Mémento Python 3 (draft, readers needed)

2012-06-05 Thread Petite Abeille

On Jun 5, 2012, at 8:56 PM, MRAB wrote:

> valeurs approchées => (not sure)

Approximation?

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


Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 5, 8:50 pm, Eelco  wrote:
> > thank you both for your replies. Unfortunately it is a pre-existing
> > file format imposed by an external system that I can't
> > change. Thank you for the code snippet.
>
> Hi Richard,
>
> Despite the fact that it is a preexisting format, it is very close
> indeed to valid YAML code.
>
> Writing your own whitespace-aware parser can be a bit of a pain, but
> since YAML does this for you, I would argue the cleanest solution
> would be to bootstrap that functionality, rather than roll your own
> solution, or to resort to hard to maintain regex voodoo.
>
> Here is my solution. As a bonus, it directly constructs a custom
> object hierarchy (obviously you would want to expand on this, but the
> essentials are there). One caveat: at the moment, the conversion to
> YAML relies on the appparent convention that instances never directly
> contain other instances, and lists never directly contain lists. This
> means all instances are list entries and get a '-' appended, and this
> just works. If this is not a general rule, youd have to keep track of
> an enclosing scope stack an emit dashes based on that. Anyway, the
> idea is there, and I believe it to be one worth looking at.
>
> 
> import yaml
>
> class A(yaml.YAMLObject):
>     yaml_tag = u'!A'
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __repr__(self):
>         return 'A' + str(self.__dict__)
>
> class B(yaml.YAMLObject):
>     yaml_tag = u'!B'
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __repr__(self):
>         return 'B' + str(self.__dict__)
>
> class C(yaml.YAMLObject):
>     yaml_tag = u'!C'
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __repr__(self):
>         return 'C' + str(self.__dict__)
>
> class TestArray(yaml.YAMLObject):
>     yaml_tag = u'!TestArray'
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __repr__(self):
>         return 'TestArray' + str(self.__dict__)
>
> class myList(yaml.YAMLObject):
>     yaml_tag = u'!myList'
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __repr__(self):
>         return 'myList' + str(self.__dict__)
>
> data = \
> """
> An instance of TestArray
>  a=a
>  b=b
>  c=c
>  List of 2 A elements:
>   Instance of A element
>    a=1
>    b=2
>    c=3
>   Instance of A element
>    d=1
>    e=2
>    f=3
>  List of 1 B elements
>   Instance of B element
>    a=1
>    b=2
>    c=3
>    List of 2 C elements
>     Instance of C element
>      a=1
>      b=2
>      c=3
>     Instance of C element
>      a=1
>      b=2
>      c=3
> An instance of TestArray
>  a=1
>  b=2
>  c=3
> """.strip()
>
> #remove trailing whitespace and seemingly erronous colon in line 5
> lines = ['  '+line.rstrip().rstrip(':') for line in data.split('\n')]
>
> def transform(lines):
>     """transform text line by line"""
>     for line in lines:
>         #regular mapping lines
>         if line.find('=') > 0:
>             yield line.replace('=', ': ')
>         #instance lines
>         p = line.find('nstance of')
>         if p > 0:
>             s = p + 11
>             e = line[s:].find(' ')
>             if e == -1: e = len(line[s:])
>             tag = line[s:s+e]
>             whitespace= line.partition(line.lstrip())[0]
>             yield whitespace[:-2]+' -'+ ' !'+tag
>         #list lines
>         p = line.find('List of')
>         if p > 0:
>             whitespace= line.partition(line.lstrip())[0]
>             yield whitespace[:-2]+'  '+ 'myList:'
>
> ##transformed = (transform( lines))
> ##for i,t in enumerate(transformed):
> ##    print '{:>3}{}'.format(i,t)
>
> transformed = '\n'.join(transform( lines))
> print transformed
>
> res = yaml.load(transformed)
> print res
> print yaml.dump(res)
> 

Hi Eelco many thanks for the reply / solution it definitely looks like
a clean way to go about it. However installing 3rd party libs like
yaml on the server I dont think is on the cards at the moment.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Your confirmation is required to leave the Python-list mailing list

2012-06-05 Thread mhagbeng
Le 05.06.2012 22:29, 
python-list-confirm+0ddf652b9a76d520bd9945a702f68cbf7a1d2...@python.org 
a écrit :

Mailing list removal confirmation notice for mailing list Python-list

We have received a request for the removal of your email address,
"mhagb...@enib.fr" from the python-list@python.org mailing list.  To
confirm that you want to be removed from this mailing list, simply
reply to this message, keeping the Subject: header intact.  Or visit
this web page:



http://mail.python.org/mailman/confirm/python-list/0ddf652b9a76d520bd9945a702f68cbf7a1d2cf0


Or include the following line -- and only the following line -- in a
message to python-list-requ...@python.org:

confirm 0ddf652b9a76d520bd9945a702f68cbf7a1d2cf0

Note that simply sending a `reply' to this message should work from
most mail readers, since that usually leaves the Subject: line in the
right form (additional "Re:" text in the Subject: is okay).

If you do not wish to be removed from this list, please simply
disregard this message.  If you think you are being maliciously
removed from the list, or have any other questions, send them to
python-list-ow...@python.org.


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


Re: Help needed with nested parsing of file into objects

2012-06-05 Thread Alain Ketterlin
richard  writes:


[I'm leaving the data in the message in case anybody has troubles going
up-thread.]

> Hi guys still struggling to get the code that was posted to me on this
> forum to work in my favour and get the output in the format shown
> above. This is what I have so far. Any help will be greatly
> apprectiated.
>
> output trying to achieve
> parsed = [
> {
>   "a":"a",
>   "b":"b",
>   "c":"c",
>   "A_elements":[
>   {
> "a":1,
> "b":2,
> "c":3
>   },
>   {
>  "a":1,
>  "b":2,
>  "c":3
>   }
>],
>   "B_elements":[
>   {
> "a":1,
> "b":2,
> "c":3,
> "C_elements":[
>  {
>  "a":1,
>  "b":2,
>  "c":3
>   },
>   {
>   "a":1,
>   "b":2,
>   "c":3
>   }
>  ]
>   }
>]
> },
>
> {
>   "a":"1",
>   "b":"2",
>   "c":"3",
> }
>
> ]
>
> file format unchangeable
>
> An instance of TestArray
>  a=a
>  b=b
>  c=c
>  List of 2 A elements:
>   Instance of A element
>a=1
>b=2
>c=3
>   Instance of A element
>d=1
>e=2
>f=3
>  List of 1 B elements
>   Instance of B element
>a=1
>b=2
>c=3
>List of 2 C elements
> Instance of C element
>  a=1
>  b=2
>  c=3
> Instance of C element
>  a=1
>  b=2
>  c=3
>
> An instance of TestArray
>  a=1
>  b=2
>  c=3
>
> def test_parser(filename):
> class Stanza:
> def __init__(self, values):
> for attr, val in values:
> setattr(self, attr, val)
>
> def build(couple):
> if "=" in couple[0]:
> attr, val = couple[0].split("=")
> return attr,val
> elif "Instance of" in couple[0]:
> match = re.search("Instance of (.+) element", couple[0])
> return ("attr_%s" % match.group(1),Stanza(couple[1]))
> elif "List of" in couple[0]:
> match = re.search("List of \d (.+) elements", couple[0])
> return ("%s_elements" % match.group(1),couple[1])

You forgot one case:

def build(couple):
if "=" in couple[0]:
attr, val = couple[0].split("=")
return attr,val
elif "Instance of" in couple[0]:
#match = re.search("Instance of (.+) element", couple[0])
#return ("attr_%s" % match.group(1),Stanza(couple[1]))
return dict(couple[1])
elif "An instance of" in couple[0]: # you forgot that case
return dict(couple[1])
elif "List of" in couple[0]:
match = re.search("List of \d (.+) elements", couple[0])
return ("%s_elements" % match.group(1),couple[1])
else:
pass # put a test here

> fo = open(filename, "r")
> RE = re.compile("( *)(.*)")
> stack = [("-",[])]
> for line in fo:
> matches = RE.match(line)
> if len(matches.group(2)) > 0:
> depth = 1 + len(matches.group(1))
> while len(stack) > depth:
> stack[-2][1].append(build(stack[-1]))
> del stack[-1]
> stack.append( (matches.group(2),[]) )
> while len(stack) > 1:
> stack[-2][1].append(stack[-1])

Change this to:

  stack[-2][1].append(build(stack[-1])) # call build() here also

> del stack[-1]
> return stack

Actually the first and only element of stack is a container: all you
need is the second element of the only tuple in stack, so:

  return stack[0][1]

and this is your list. If you need it pretty printed, you'll have to
work the hierarchy.

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


Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 5, 9:40 pm, Alain Ketterlin 
wrote:
> richard  writes:
>
> [I'm leaving the data in the message in case anybody has troubles going
> up-thread.]
>
>
>
>
>
>
>
>
>
> > Hi guys still struggling to get the code that was posted to me on this
> > forum to work in my favour and get the output in the format shown
> > above. This is what I have so far. Any help will be greatly
> > apprectiated.
>
> > output trying to achieve
> > parsed = [
> >     {
> >       "a":"a",
> >       "b":"b",
> >       "c":"c",
> >       "A_elements":[
> >           {
> >             "a":1,
> >             "b":2,
> >             "c":3
> >           },
> >           {
> >              "a":1,
> >              "b":2,
> >              "c":3
> >           }
> >        ],
> >       "B_elements":[
> >           {
> >             "a":1,
> >             "b":2,
> >             "c":3,
> >             "C_elements":[
> >                  {
> >                      "a":1,
> >                      "b":2,
> >                      "c":3
> >                   },
> >                   {
> >                       "a":1,
> >                       "b":2,
> >                       "c":3
> >                   }
> >              ]
> >           }
> >        ]
> >     },
>
> >     {
> >       "a":"1",
> >       "b":"2",
> >       "c":"3",
> >     }
>
> > ]
>
> > file format unchangeable
>
> > An instance of TestArray
> >  a=a
> >  b=b
> >  c=c
> >  List of 2 A elements:
> >   Instance of A element
> >    a=1
> >    b=2
> >    c=3
> >   Instance of A element
> >    d=1
> >    e=2
> >    f=3
> >  List of 1 B elements
> >   Instance of B element
> >    a=1
> >    b=2
> >    c=3
> >    List of 2 C elements
> >     Instance of C element
> >      a=1
> >      b=2
> >      c=3
> >     Instance of C element
> >      a=1
> >      b=2
> >      c=3
>
> > An instance of TestArray
> >  a=1
> >  b=2
> >  c=3
>
> > def test_parser(filename):
> >     class Stanza:
> >         def __init__(self, values):
> >             for attr, val in values:
> >                 setattr(self, attr, val)
>
> >     def build(couple):
> >         if "=" in couple[0]:
> >             attr, val = couple[0].split("=")
> >             return attr,val
> >         elif "Instance of" in couple[0]:
> >             match = re.search("Instance of (.+) element", couple[0])
> >             return ("attr_%s" % match.group(1),Stanza(couple[1]))
> >         elif "List of" in couple[0]:
> >             match = re.search("List of \d (.+) elements", couple[0])
> >             return ("%s_elements" % match.group(1),couple[1])
>
> You forgot one case:
>
>     def build(couple):
>         if "=" in couple[0]:
>             attr, val = couple[0].split("=")
>             return attr,val
>         elif "Instance of" in couple[0]:
>             #match = re.search("Instance of (.+) element", couple[0])
>             #return ("attr_%s" % match.group(1),Stanza(couple[1]))
>             return dict(couple[1])
>         elif "An instance of" in couple[0]: # you forgot that case
>             return dict(couple[1])
>         elif "List of" in couple[0]:
>             match = re.search("List of \d (.+) elements", couple[0])
>             return ("%s_elements" % match.group(1),couple[1])
>         else:
>             pass # put a test here
>
> >     fo = open(filename, "r")
> >     RE = re.compile("( *)(.*)")
> >     stack = [("-",[])]
> >     for line in fo:
> >         matches = RE.match(line)
> >         if len(matches.group(2)) > 0:
> >             depth = 1 + len(matches.group(1))
> >             while len(stack) > depth:
> >                 stack[-2][1].append(build(stack[-1]))
> >                 del stack[-1]
> >             stack.append( (matches.group(2),[]) )
> >     while len(stack) > 1:
> >         stack[-2][1].append(stack[-1])
>
> Change this to:
>
>           stack[-2][1].append(build(stack[-1])) # call build() here also
>
> >         del stack[-1]
> >     return stack
>
> Actually the first and only element of stack is a container: all you
> need is the second element of the only tuple in stack, so:
>
>       return stack[0][1]
>
> and this is your list. If you need it pretty printed, you'll have to
> work the hierarchy.
>
> -- Alain.

Hi Alain thanks for the reply. With regards to the missing case "An
Instance of" im not sure where/ how that is working as the case i put
in originally "Instance of" is in the file and been handled in the
previous case. Also when running the final solution im getting a list
of [None, None] as the final stack? just busy debugging it to see
whats going wrong. But sorry should have been clearer with regards to
the format mentioned above. The objects are been printed out as dicts
so where you put in

elif "An Instance of" in couple[0]:
return dict(couple[1])

should still be ?
elif "Instance of" in couple[0]:
match = re.search("Instance of (.+) element", couple[0])
return ("attr_%s" % match.group(1),Stanza(couple[1])) 

Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 5, 9:40 pm, Alain Ketterlin 
wrote:
> richard  writes:
>
> [I'm leaving the data in the message in case anybody has troubles going
> up-thread.]
>
>
>
>
>
>
>
>
>
> > Hi guys still struggling to get the code that was posted to me on this
> > forum to work in my favour and get the output in the format shown
> > above. This is what I have so far. Any help will be greatly
> > apprectiated.
>
> > output trying to achieve
> > parsed = [
> >     {
> >       "a":"a",
> >       "b":"b",
> >       "c":"c",
> >       "A_elements":[
> >           {
> >             "a":1,
> >             "b":2,
> >             "c":3
> >           },
> >           {
> >              "a":1,
> >              "b":2,
> >              "c":3
> >           }
> >        ],
> >       "B_elements":[
> >           {
> >             "a":1,
> >             "b":2,
> >             "c":3,
> >             "C_elements":[
> >                  {
> >                      "a":1,
> >                      "b":2,
> >                      "c":3
> >                   },
> >                   {
> >                       "a":1,
> >                       "b":2,
> >                       "c":3
> >                   }
> >              ]
> >           }
> >        ]
> >     },
>
> >     {
> >       "a":"1",
> >       "b":"2",
> >       "c":"3",
> >     }
>
> > ]
>
> > file format unchangeable
>
> > An instance of TestArray
> >  a=a
> >  b=b
> >  c=c
> >  List of 2 A elements:
> >   Instance of A element
> >    a=1
> >    b=2
> >    c=3
> >   Instance of A element
> >    d=1
> >    e=2
> >    f=3
> >  List of 1 B elements
> >   Instance of B element
> >    a=1
> >    b=2
> >    c=3
> >    List of 2 C elements
> >     Instance of C element
> >      a=1
> >      b=2
> >      c=3
> >     Instance of C element
> >      a=1
> >      b=2
> >      c=3
>
> > An instance of TestArray
> >  a=1
> >  b=2
> >  c=3
>
> > def test_parser(filename):
> >     class Stanza:
> >         def __init__(self, values):
> >             for attr, val in values:
> >                 setattr(self, attr, val)
>
> >     def build(couple):
> >         if "=" in couple[0]:
> >             attr, val = couple[0].split("=")
> >             return attr,val
> >         elif "Instance of" in couple[0]:
> >             match = re.search("Instance of (.+) element", couple[0])
> >             return ("attr_%s" % match.group(1),Stanza(couple[1]))
> >         elif "List of" in couple[0]:
> >             match = re.search("List of \d (.+) elements", couple[0])
> >             return ("%s_elements" % match.group(1),couple[1])
>
> You forgot one case:
>
>     def build(couple):
>         if "=" in couple[0]:
>             attr, val = couple[0].split("=")
>             return attr,val
>         elif "Instance of" in couple[0]:
>             #match = re.search("Instance of (.+) element", couple[0])
>             #return ("attr_%s" % match.group(1),Stanza(couple[1]))
>             return dict(couple[1])
>         elif "An instance of" in couple[0]: # you forgot that case
>             return dict(couple[1])
>         elif "List of" in couple[0]:
>             match = re.search("List of \d (.+) elements", couple[0])
>             return ("%s_elements" % match.group(1),couple[1])
>         else:
>             pass # put a test here
>
> >     fo = open(filename, "r")
> >     RE = re.compile("( *)(.*)")
> >     stack = [("-",[])]
> >     for line in fo:
> >         matches = RE.match(line)
> >         if len(matches.group(2)) > 0:
> >             depth = 1 + len(matches.group(1))
> >             while len(stack) > depth:
> >                 stack[-2][1].append(build(stack[-1]))
> >                 del stack[-1]
> >             stack.append( (matches.group(2),[]) )
> >     while len(stack) > 1:
> >         stack[-2][1].append(stack[-1])
>
> Change this to:
>
>           stack[-2][1].append(build(stack[-1])) # call build() here also
>
> >         del stack[-1]
> >     return stack
>
> Actually the first and only element of stack is a container: all you
> need is the second element of the only tuple in stack, so:
>
>       return stack[0][1]
>
> and this is your list. If you need it pretty printed, you'll have to
> work the hierarchy.
>
> -- Alain.

Hi Alain, thanks for the reply. Amended the code and just busy
debugging but the stack i get back justs return [None, None]. Also
should have been clearer when i mentioned the format above the dicts
are actually objects instantaited from classes and just printed out as
obj.__dict__ just for representation putposes. so where you have
replaced the following i presume this was because of my format
confusion. Thanks

> elif "Instance of" in couple[0]:
> match = re.search("Instance of (.+) element", couple[0])
> return ("attr_%s" % match.group(1),Stanza(couple[1])) 
> #instantiating new object and setting attributes
>
with
> elif "Instance of" in couple[0]:
> #match = re.search("Instance of (.+) element", couple[0])
>  

Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 5, 10:21 pm, richard  wrote:
> On Jun 5, 9:40 pm, Alain Ketterlin 
> wrote:
>
>
>
>
>
>
>
>
>
> > richard  writes:
>
> > [I'm leaving the data in the message in case anybody has troubles going
> > up-thread.]
>
> > > Hi guys still struggling to get the code that was posted to me on this
> > > forum to work in my favour and get the output in the format shown
> > > above. This is what I have so far. Any help will be greatly
> > > apprectiated.
>
> > > output trying to achieve
> > > parsed = [
> > >     {
> > >       "a":"a",
> > >       "b":"b",
> > >       "c":"c",
> > >       "A_elements":[
> > >           {
> > >             "a":1,
> > >             "b":2,
> > >             "c":3
> > >           },
> > >           {
> > >              "a":1,
> > >              "b":2,
> > >              "c":3
> > >           }
> > >        ],
> > >       "B_elements":[
> > >           {
> > >             "a":1,
> > >             "b":2,
> > >             "c":3,
> > >             "C_elements":[
> > >                  {
> > >                      "a":1,
> > >                      "b":2,
> > >                      "c":3
> > >                   },
> > >                   {
> > >                       "a":1,
> > >                       "b":2,
> > >                       "c":3
> > >                   }
> > >              ]
> > >           }
> > >        ]
> > >     },
>
> > >     {
> > >       "a":"1",
> > >       "b":"2",
> > >       "c":"3",
> > >     }
>
> > > ]
>
> > > file format unchangeable
>
> > > An instance of TestArray
> > >  a=a
> > >  b=b
> > >  c=c
> > >  List of 2 A elements:
> > >   Instance of A element
> > >    a=1
> > >    b=2
> > >    c=3
> > >   Instance of A element
> > >    d=1
> > >    e=2
> > >    f=3
> > >  List of 1 B elements
> > >   Instance of B element
> > >    a=1
> > >    b=2
> > >    c=3
> > >    List of 2 C elements
> > >     Instance of C element
> > >      a=1
> > >      b=2
> > >      c=3
> > >     Instance of C element
> > >      a=1
> > >      b=2
> > >      c=3
>
> > > An instance of TestArray
> > >  a=1
> > >  b=2
> > >  c=3
>
> > > def test_parser(filename):
> > >     class Stanza:
> > >         def __init__(self, values):
> > >             for attr, val in values:
> > >                 setattr(self, attr, val)
>
> > >     def build(couple):
> > >         if "=" in couple[0]:
> > >             attr, val = couple[0].split("=")
> > >             return attr,val
> > >         elif "Instance of" in couple[0]:
> > >             match = re.search("Instance of (.+) element", couple[0])
> > >             return ("attr_%s" % match.group(1),Stanza(couple[1]))
> > >         elif "List of" in couple[0]:
> > >             match = re.search("List of \d (.+) elements", couple[0])
> > >             return ("%s_elements" % match.group(1),couple[1])
>
> > You forgot one case:
>
> >     def build(couple):
> >         if "=" in couple[0]:
> >             attr, val = couple[0].split("=")
> >             return attr,val
> >         elif "Instance of" in couple[0]:
> >             #match = re.search("Instance of (.+) element", couple[0])
> >             #return ("attr_%s" % match.group(1),Stanza(couple[1]))
> >             return dict(couple[1])
> >         elif "An instance of" in couple[0]: # you forgot that case
> >             return dict(couple[1])
> >         elif "List of" in couple[0]:
> >             match = re.search("List of \d (.+) elements", couple[0])
> >             return ("%s_elements" % match.group(1),couple[1])
> >         else:
> >             pass # put a test here
>
> > >     fo = open(filename, "r")
> > >     RE = re.compile("( *)(.*)")
> > >     stack = [("-",[])]
> > >     for line in fo:
> > >         matches = RE.match(line)
> > >         if len(matches.group(2)) > 0:
> > >             depth = 1 + len(matches.group(1))
> > >             while len(stack) > depth:
> > >                 stack[-2][1].append(build(stack[-1]))
> > >                 del stack[-1]
> > >             stack.append( (matches.group(2),[]) )
> > >     while len(stack) > 1:
> > >         stack[-2][1].append(stack[-1])
>
> > Change this to:
>
> >           stack[-2][1].append(build(stack[-1])) # call build() here also
>
> > >         del stack[-1]
> > >     return stack
>
> > Actually the first and only element of stack is a container: all you
> > need is the second element of the only tuple in stack, so:
>
> >       return stack[0][1]
>
> > and this is your list. If you need it pretty printed, you'll have to
> > work the hierarchy.
>
> > -- Alain.
>
> Hi Alain, thanks for the reply. Amended the code and just busy
> debugging but the stack i get back justs return [None, None]. Also
> should have been clearer when i mentioned the format above the dicts
> are actually objects instantaited from classes and just printed out as
> obj.__dict__ just for representation putposes. so where you have
> replaced the following i presume this was because of my format
> confusion. Thanks
>
>
>
>
>
>
>
>
>
> >         elif "I

Re: Help needed with nested parsing of file into objects

2012-06-05 Thread Alain Ketterlin
richard  writes:

>> > An instance of TestArray
>> >  a=a
>> >  b=b
>> >  c=c
>> >  List of 2 A elements:
>> >   Instance of A element
>> >    a=1
>> >    b=2
>> >    c=3
>> >   Instance of A element
>> >    d=1
>> >    e=2
>> >    f=3
>> >  List of 1 B elements
>> >   Instance of B element
>> >    a=1
>> >    b=2
>> >    c=3
>> >    List of 2 C elements
>> >     Instance of C element
>> >      a=1
>> >      b=2
>> >      c=3
>> >     Instance of C element
>> >      a=1
>> >      b=2
>> >      c=3
[...]

> Hi Alain thanks for the reply. With regards to the missing case "An
> Instance of" im not sure where/ how that is working as the case i put
> in originally "Instance of" is in the file and been handled in the
> previous case.

Both cases are different in your example above. Top level elements are
labeled "An instance ...", whereas "inner" instances are labeled
"Instance of ...".

> Also when running the final solution im getting a list of [None, None]
> as the final stack?

There's only one way this can happen: by falling through to the last
case of build(). Check the regexps etc. again.

> just busy debugging it to see whats going wrong. But sorry should have
> been clearer with regards to the format mentioned above. The objects
> are been printed out as dicts so where you put in
>
> elif "An Instance of" in couple[0]:
> return dict(couple[1])
>
> should still be ?
> elif "Instance of" in couple[0]:
> match = re.search("Instance of (.+) element", couple[0])
> return ("attr_%s" % match.group(1),Stanza(couple[1])) #
> instantiating new stanza object and setting attributes.

Your last "Instance of..." case is correct, but "An instance..." is
different, because there's no containing object, so it's probably more
like: return Stanza(couple[1]).

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


Re: English version for Mémento Python 3 (draft, readers needed)

2012-06-05 Thread MRAB

On 05/06/2012 21:01, Petite Abeille wrote:


On Jun 5, 2012, at 8:56 PM, MRAB wrote:


 valeurs approchées =>  (not sure)


Approximation?


I think I understand now:

nombres flottants… valeurs approchées! => float-point numbers… 
approximate values!

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


Re: Help needed with nested parsing of file into objects

2012-06-05 Thread richard
On Jun 5, 10:33 pm, Alain Ketterlin 
wrote:
> richard  writes:
> >> > An instance of TestArray
> >> >  a=a
> >> >  b=b
> >> >  c=c
> >> >  List of 2 A elements:
> >> >   Instance of A element
> >> >    a=1
> >> >    b=2
> >> >    c=3
> >> >   Instance of A element
> >> >    d=1
> >> >    e=2
> >> >    f=3
> >> >  List of 1 B elements
> >> >   Instance of B element
> >> >    a=1
> >> >    b=2
> >> >    c=3
> >> >    List of 2 C elements
> >> >     Instance of C element
> >> >      a=1
> >> >      b=2
> >> >      c=3
> >> >     Instance of C element
> >> >      a=1
> >> >      b=2
> >> >      c=3
>
> [...]
>
> > Hi Alain thanks for the reply. With regards to the missing case "An
> > Instance of" im not sure where/ how that is working as the case i put
> > in originally "Instance of" is in the file and been handled in the
> > previous case.
>
> Both cases are different in your example above. Top level elements are
> labeled "An instance ...", whereas "inner" instances are labeled
> "Instance of ...".
>
> > Also when running the final solution im getting a list of [None, None]
> > as the final stack?
>
> There's only one way this can happen: by falling through to the last
> case of build(). Check the regexps etc. again.
>
> > just busy debugging it to see whats going wrong. But sorry should have
> > been clearer with regards to the format mentioned above. The objects
> > are been printed out as dicts so where you put in
>
> >         elif "An Instance of" in couple[0]:
> >             return dict(couple[1])
>
> >         should still be ?
> >         elif "Instance of" in couple[0]:
> >             match = re.search("Instance of (.+) element", couple[0])
> >             return ("attr_%s" % match.group(1),Stanza(couple[1])) #
> > instantiating new stanza object and setting attributes.
>
> Your last "Instance of..." case is correct, but "An instance..." is
> different, because there's no containing object, so it's probably more
> like: return Stanza(couple[1]).
>
> -- Alain.

A big thank you to everyone who has helped me tackle / shed light on
this problem it is working great. Much appreciated.

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


How to exec() a string like interactive python does?

2012-06-05 Thread News123

If I start Python in interactive mode,
and I yype the commands,
'a=3', 'a', 'print a'


Then the  output would look like:
>>> a = 3
>>> a
3
>>>  print a
3


Now within an application I'd like to achieve exactly this behaviour
Meaning, that
- for assignments nothing is displayed
- for expressions the result of the exprission displayed
- and statements like print statements would be executed


The only thing, that I came up with is following code and that would
even print out results for 'a=3', where the normal interactive python 
would not echo any result.


for cmd in [ 'a=3', 'a', 'print a' ] :
try:
print('>>> ' + cmd)
exec('__rslt = ' + cmd)
if __rslt is not None:
print repr(__rslt)
except SyntaxError:
exec(cmd)

The result would look like:
>>> a=3
3
>>> a
3
>>> print a
3
>>>


Is There anything better?





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


Re: How to exec() a string like interactive python does?

2012-06-05 Thread Devin Jeanpierre
>>>
>>> def myexec(s):
... eval(compile(s, '', 'single'))
...
>>> x = 3
>>> myexec('x = 4')
>>> myexec('x')
3
>>> myexec('print x')
3
>>>

On Tue, Jun 5, 2012 at 6:12 PM, News123  wrote:
> If I start Python in interactive mode,
> and I yype the commands,
> 'a=3', 'a', 'print a'
>
>
> Then the  output would look like:
 a = 3
 a
> 3
  print a
> 3
>
>
> Now within an application I'd like to achieve exactly this behaviour
> Meaning, that
> - for assignments nothing is displayed
> - for expressions the result of the exprission displayed
> - and statements like print statements would be executed
>
>
> The only thing, that I came up with is following code and that would
> even print out results for 'a=3', where the normal interactive python would
> not echo any result.
>
> for cmd in [ 'a=3', 'a', 'print a' ] :
>    try:
>        print('>>> ' + cmd)
>        exec('__rslt = ' + cmd)
>        if __rslt is not None:
>            print repr(__rslt)
>    except SyntaxError:
>        exec(cmd)
>
> The result would look like:
 a=3
> 3
 a
> 3
 print a
> 3

>
>
> Is There anything better?
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to exec() a string like interactive python does?

2012-06-05 Thread Steven D'Aprano
On Wed, 06 Jun 2012 00:12:00 +0200, News123 wrote:

> If I start Python in interactive mode, and I yype the commands,
> 'a=3', 'a', 'print a'
> 
> 
> Then the  output would look like:
>  >>> a = 3
>  >>> a
> 3
>  >>>  print a
> 3
> 
> 
> Now within an application I'd like to achieve exactly this behaviour

Before you reinvent the wheel, see the cmd and code modules.

http://docs.python.org/library/cmd.html
http://docs.python.org/library/code.html



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


Python Tree datastructure comparison

2012-06-05 Thread Dan Stromberg
I've put together a comparison of some tree datastructures for Python, with
varied runtime and varied workload:

http://stromberg.dnsalias.org/~strombrg/python-tree-and-heap-comparison/

I hope to find time to add heaps to the article at some point, but for now,
it only covers trees and the treap.

The short version:

   1. The 2-3 tree gave incorrect results, so I eliminated it.  This may or
   may not have been my fault.
   2. The Red-black tree was performing so slowly that it was making the
   graphs hard to read, so I eliminated it.  It actually seemed to be doing
   pretty well at first, until I realized that garbage collections were
   becoming very slow with red-black trees.
   3. The top three performers were, under various workloads and with
   various runtimes: The AVL Tree, The Splay Tree and The Treap.
   4. The Treap was consistently either in first or second place.
   5. All the datastructures examined were ported to python 3 in such a way
   that they would continue to work on python 2 - I've at times taken
   liberties like allowing log(n) range's, which of course are eagerly
   evaluated in python 2.  The modules were also modified to pass pylint.

These are all trees (and the treap), for now, with dictionary-like
interfaces, that allow you to do things like look up the least (or
greatest) value in log(n) time.  The need for such a datastructure is
uncommon, but does come up from time to time - implementing a cache is
foremost in my mind.  If you just need fast lookups without any particular
ordering, you're almost always going to be better off with a hash table
(dictionary).
-- 
http://mail.python.org/mailman/listinfo/python-list


mistake in python tutorial

2012-06-05 Thread Miriam Gomez Rios
Hello, I think that the example in section 4.4 in the tutorial for python 2.7X 
is wrong.

http://docs.python.org/tutorial/controlflow.html



It will end up printing this if you run the exact code listed in the tutorial.



3 is a prime number

4 equals 2*2

5 is a prime number

5 is a prime number

5 is a prime number

6 equals 2 * 3

7 is a prime number

7 is a prime number

7 is a prime number

7 is a prime number

7 is a prime number

8 equals 2*4

9 is a prime number

9 equals 3*3



I believe it is because the is no break in " else print n is a prime number" and

it never prints anything about number 2 because the second for is like 
range(2,2)

which is empty so it does nothing.




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


Re: mistake in python tutorial

2012-06-05 Thread Dave Angel
On 06/05/2012 09:43 PM, Miriam Gomez Rios wrote:
> Hello, I think that the example in section 4.4 in the tutorial for python 
> 2.7X is wrong.
>
> http://docs.python.org/tutorial/controlflow.html
>
>
>
> It will end up printing this if you run the exact code listed in the tutorial.
>
>
>
> 3 is a prime number
>
> 4 equals 2*2
>
> 5 is a prime number
>
> 5 is a prime number
>
> 5 is a prime number
>
> 6 equals 2 * 3
>
> 7 is a prime number
>
> 7 is a prime number
>
> 7 is a prime number
>
> 7 is a prime number
>
> 7 is a prime number
>
> 8 equals 2*4
>
> 9 is a prime number
>
> 9 equals 3*3
>
>
>
> I believe it is because the is no break in " else print n is a prime number" 
> and
>
> it never prints anything about number 2 because the second for is like 
> range(2,2)
>
> which is empty so it does nothing.
>
>

Hate to tell you, but the example works as it exists on the website.  If
you got your output, you must have messed up the indentation, which is
VERY important in python.

In particular, the else clause has to line up with the for statement,
NOT with the if statement.

If it helps, this is the correct indentation.  Paste it into a file, and
run it.

for n in range(2, 10):
 for x in range(2, n):
 if n % x == 0:
 print n, 'equals', x, '*', n/x
 break
 else:
 # loop fell through without finding a factor
 print n, 'is a prime number'

-- 
DaveA

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


Re: mistake in python tutorial

2012-06-05 Thread MRAB

On 06/06/2012 03:00, Dave Angel wrote:

On 06/05/2012 09:43 PM, Miriam Gomez Rios wrote:

 Hello, I think that the example in section 4.4 in the tutorial for python 2.7X 
is wrong.

 http://docs.python.org/tutorial/controlflow.html



 It will end up printing this if you run the exact code listed in the tutorial.



 3 is a prime number

 4 equals 2*2

 5 is a prime number

 5 is a prime number

 5 is a prime number

 6 equals 2 * 3

 7 is a prime number

 7 is a prime number

 7 is a prime number

 7 is a prime number

 7 is a prime number

 8 equals 2*4

 9 is a prime number

 9 equals 3*3



 I believe it is because the is no break in " else print n is a prime number" 
and

 it never prints anything about number 2 because the second for is like 
range(2,2)

 which is empty so it does nothing.




Hate to tell you, but the example works as it exists on the website.  If
you got your output, you must have messed up the indentation, which is
VERY important in python.

In particular, the else clause has to line up with the for statement,
NOT with the if statement.

If it helps, this is the correct indentation.  Paste it into a file, and
run it.

for n in range(2, 10):
  for x in range(2, n):
  if n % x == 0:
  print n, 'equals', x, '*', n/x
  break
  else:
  # loop fell through without finding a factor
  print n, 'is a prime number'


I can confirm that the OP's output is what you get when the 'else' is
indented the same as the 'if'.
--
http://mail.python.org/mailman/listinfo/python-list


Re: English version for Mémento Python 3 (draft, readers needed)

2012-06-05 Thread Paul Rubin
Laurent Pointal  writes:
>> There are a few other things like that, and I'll try to look more
>> carefully tonight, I can't spend more time on it right now.
> I updated the document into 1.0.5a (and fix some other errors).

A few more things:

In "Base types" section: 
   unmodifiable => immutable
  (both are correct but immutable is a clearer technical term)

In "Container types": 
   unmodifiable => immutableas above
   dictionnary => dictionary

In "Identifiers":
   min/MAJ case discrimination => lower/UPPER case sensitive

In "Conversions":
   see verso => see other side
 ("verso" is not wrong, but it's an unusual word in US English)
   logial => logical

In "Sequences indexing":
   negative index -4 => [the formatting is broken]

In "Boolean Logic"
   twice simultaneously => both simultaneously

In "Maths"
   remain => modulo

[page 2]

In "Conditional loop statement"
  care to inifinite loops! => be careful of infinite loops!

In "Display / Input"
  recto => other side(like "verso" further up)
  littéral => literal

In "Files"
  don't miss to close file => don't forget to close the file
[but you might mention the "with" statement]

In "Function definition"
  bloc => block
  (« black box »)  => ("black box")
[English speakers may not recognize « » symbols]
  
In "Generator of int sequences"
  You might mention that range makes a generator only in Python 3.
  In Python 2 it makes an actual list and xrange makes a generator.
-- 
http://mail.python.org/mailman/listinfo/python-list


KeyError: '13'

2012-06-05 Thread Phanindra Ramesh Challa
I am trying to run a python program. It is giving the KeyError: '13'. I
have no clue regarding this error.
 this is the python code relevant to the error:

dpi = 100
bold = 0
italic = 0
mono = 0
comment = ""
dbname = "font.db"

for o, a in opts:
if o == '-b': bold = 1
if o == '-i': italic = 1
if o == '-m': mono = 1
if o == '-d': dpi = int (a)
if o == '-c': comment = string.join (string.split (a), " ")
if o == '-g': dbname = a

fontname = args[0]
pixel_size = int (args[1])

point_size = int (pixel_size * 72.27 / dpi + 0.5)

# Approximate average glyph width.
avg_width = pixel_size * 17 / 24

db = anydbm.open (dbname, "r")
codes = loads (db [str (pixel_size)])

And the error is :
python2 ../../../mk_bdf.py -c "Converted from fonts of Computer Modern
family (C) 1979-1985 Donald E. Knuth and others." -b  'TeX Sans' 13 >
tex09sb.bdf
Traceback (most recent call last):
  File "../../../mk_bdf.py", line 108, in 
codes = loads (db [str (pixel_size)])
  File "/usr/lib/python2.7/bsddb/__init__.py", line 270, in __getitem__
return _DeadlockWrap(lambda: self.db[key])  # self.db[key]
  File "/usr/lib/python2.7/bsddb/dbutils.py", line 68, in DeadlockWrap
return function(*_args, **_kwargs)
  File "/usr/lib/python2.7/bsddb/__init__.py", line 270, in 
return _DeadlockWrap(lambda: self.db[key])  # self.db[key]
KeyError: '13'



 Anybody please help me in running the program.
-- 
http://mail.python.org/mailman/listinfo/python-list