Python(x,y) 64 bit

2016-04-27 Thread Pierre
Hello,

I installed Python(x,y) 64 bit version and ran it using a library that requires 
Python 64 bit. 
I got an error which indicated that I am using Python 32 bit.

So, is the python used by Python(x,y) 64 bit, using Python 64 or 32 bit?

Thanks



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


Re: Python(x,y) 64 bit

2016-04-27 Thread Pierre
On Wednesday, April 27, 2016 at 11:17:32 AM UTC-4, Zachary Ware wrote:
> Hi Pierre,
> 
> On Wed, Apr 27, 2016 at 6:23 AM, Pierre  wrote:
> > Hello,
> >
> > I installed Python(x,y) 64 bit version and ran it using a library that 
> > requires Python 64 bit.
> > I got an error which indicated that I am using Python 32 bit.
> >
> > So, is the python used by Python(x,y) 64 bit, using Python 64 or 32 bit?
> 
> You can check by doing `python -c "import sys;print(sys.maxsize ==
> 2**63-1)"`.  You'll get True for 64-bit, False for 32-bit.  There's a
> possibility that you've gotten a misleading error message, though.
> What version of Python(x,y) are you using, and what library?
> 
> -- 
> Zach

Zach,

I did check and it looks like the Python(x,y) 64 distribution I downloaded uses 
a 32 bit Python.
The question is if there is ANY Python(x,y) 64 distribution that uses the 64 
bit python version.
I looked it up online and could not find anything related to this issue
-- 
https://mail.python.org/mailman/listinfo/python-list


Properties transfer between instances of different classes, without subclassing

2005-12-09 Thread Pierre
Folks,
I'm pretty new to OOP, so I still have problems with inheritance and
delegation.
I defined 2 Numeric MaskedArray subclasses, as:

class Temp(MA,object):
   def __init__(self,data):
   self = MA.__init__(self,data)
   cold = property(fget lambda self:masked_where(self<10,self)
   warm = property(fget lambda self:masked_where(self>20,self)

class Tabl(MA,object):
def __init__(self,vector)
self.vector=vector
tabl = apply_processing_functions_to(vector)
self = MA.__init__(self,tabl)

where 'data' and 'vector' are themselves masked arrays.

I'd like to add the properties of the argument of an instance of Tabl
to this instance, only if the properties are not already defined.
For example, I create an instance of 'Temp' (say, 'tempv'), and
instance of 'Tabl' (say 'tablv'), this latter initialized with the
former.
v = arange(5,26)
tempv = Temp(v)
tabv = tabulated(tempv)

Ideally, 'tabv.cold' would give me 'tabv', masked where the values are
<10.
I don't want to make 'Tabl' a subclass of 'Temp'. I'd like to use it
more generically, so that when I define a 3rd class 'Color', I could
initiate 'Tabv' with an instance of 'Color', accessing the 'Color'
properties without the 'Temp' properties.

In short, I want to pass the properties of an instance attribute to the
instance...

Any ideas/comments will be welcome

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


bsddb : python, index, cursor and get

2007-11-13 Thread Pierre
Hello,

I'm having problems to use the get method on a cursor with an index
(secondary database). I've read Oracle's docs but there are mainly in C,
JAVA and C++. So no python docs!

actually, that's what I'm trying to do :

ret = cursor.get(key='blabla', data='2007-10-30', flags=0, dlen=-1, 
doff=-1)

this does not work.


the code above this line is :

### snip
def getDate(priKey, priData):
date = string.split(priData, ' ')[1]
return date

TheDB = db.DB()
TheDB.open(filename_pri, None, db.DB_BTREE, db.DB_RDONLY)

TheIDX = db.DB()
TheIDX.open(filename_idx2, None, db.DB_BTREE, db.DB_RDONLY)

TheDB.associate(TheIDX, getDate)


# get database cursor and print out database content
cursor = TheIDX.cursor()
### snip

Does anybody have some sample code which performs a lookup in a database
with an index using a cursor in Python?

Thanks a lot
-- 
http://mail.python.org/mailman/listinfo/python-list


detecting disc serial number without win32

2007-12-10 Thread PiErre
Hi,
  I have to run a python script on a Linux machine. This script was
developed on a windows workstation and it
uses the win32 library to detect the cd (or dvd) serial number (in the
- format).
How can I change the script to do the same task on linux?
I found an old post on the same task [ "(Joliet) volume name and
serial number" on  26 Feb 2003 ]
but without answer...
Any chance there is now a way of implement such a low-level feature?
TIA!
bye,
   PiErre
-- 
http://mail.python.org/mailman/listinfo/python-list


How to customize getattr(obj, prop) function ?

2006-05-17 Thread Pierre
Hi,

Sorry in advance, english is not my main language :/

I'd like to customize the result obtained by getattr on an object : if
the object has the requested property then return it BUT if the object
doesn't has actually this property return something else.

In my case, I can't use getattr(object, property, default_value).

I tried to write a class with a __getattr__ method and even a
__getattribute__ method but this doesn't do what I want

Maybe I didn't correctly understand this :
http://docs.python.org/ref/attribute-access.html

Here is a piece of my code :
=
class myclass:
"""docstring"""

a = 'aa'
b = 'bb'

def __getattr___(self, ppt):
"""getattr"""
if hasattr(self, ppt):
return self.ppt
else:
return "my custom computed result"

def __getattribute__(self, ppt):
"""getattribute"""
if hasattr(self, ppt):
return self.ppt
else:
return "my custom computed result"

if __name__ == "__main__":

d = myclass()
p1 = getattr(d, "a")
print p1
p2 = getattr(d, "b")
print p2
p3 = getattr(d, "c")
print p3


I get an AttributeError when accessing to the property named "c".

Any explanation/solution to my problem ?

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


Re: How to customize getattr(obj, prop) function ?

2006-05-17 Thread Pierre
Nop I get the same AttributeError when I try to access to the property
"c"...

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


Re: How to customize getattr(obj, prop) function ?

2006-05-17 Thread Pierre
I'm using python 2.4.3.

I removed the method __getattribute__

The mistake was my 3rd underscore :S sorry for wasting your time...

The problem is solved ! Thx all !

PS: Richard youre message are displayed 3 times ?!

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


Re: How to customize getattr(obj, prop) function ?

2006-05-18 Thread Pierre
I don't want to use getattr(object, property, default_value) because
I'm using external code and I don't want to modify or patch it. In this
code, the call is getattr(object, property).

On my objects, I must provide default values depending on the property
that was requested, the default value is not always the same.

And Yes I understand that obj.a is equivalent to getattr(obj, 'a') BUT
the difference between class attribute and instance attribute... :S

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


Matplotlib patches collection + alpha face

2010-03-29 Thread Pierre
Hello,

I would like to draw on the same axes several patches (rectangle) with
different alpha-face (transparency)...
Anyone has an idea ?
In particular, I would like to use the class PatchCollection but it
seems that the alpha property is common to all the patches...

Thanks for your help.
-- 
http://mail.python.org/mailman/listinfo/python-list


[BarCamp] WebWorkersCamp BarCamp: NodeJS, NoSQL, Message Queues, Asynchronous programming, Web Sockets, Distributed Applications, Decentralized Social Networks, buzzword generators...

2010-05-17 Thread Pierre
Hello,

AF83 will be holding a barcamp event on Saturday afternoon, July 3rd
in Paris (in La Cantine, a famous Parisian tech place). We wanted to
let you know about this event and tell you that you would be most
welcome if you could join us on that day.

In the ever-growing context of real-time web and multiplying
webservices, websites as they are now designed are hardly scalable, or
at high costs. So we thought appropriate to hold an event to discuss
the technologies which will allow us to code differently in order to
solve these issues.

Our guests will be invited to share their experience in asynchronous
programming (server-side javascript with NodeJS, Python’s Tornado,
Ruby’s Event Machine, etc.) as well as Websockets, NoSQL databases,
queues, XMPP and others.

We’d be thrilled to have you amongst us and hear your story on this
matter! We thought this could be the opportunity for you to tell us
about your work and learn from other developers. Would you be
interested in coming and, if you wish, leading a workshop?
Then register on http://barcamp.org/WebWorkersCamp .

We’re looking forward to hearing from you soon,

Thank you,
The AF83 team.
-- 
http://mail.python.org/mailman/listinfo/python-list


sub-list extraction, logical indexation

2009-08-18 Thread Pierre
Hello Everyone,

I would like to know if it is possible to extract a sub-list from a
list ?

typically if :

L =[[1, 2, 3],[4, 5, 6],[3] ]

How to extract easily the elements 0 and 2 of L in order to get :

L2 =[[1, 2, 3],[3] ]

Moreover, I would like to know if it is possible to use logical
indexation such that :

index = [ True, False, True]
L2 = L

or usual indexation, something like
index=[0, 2]
L2 = L

I tried, but failed...
Thanks for your help

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


difference between 2 arrays

2009-08-19 Thread Pierre
Hello,

I would like to know how to find the difference (set operation)
between 2 arrays :

a = array([1,2, 3,2,5,2])
b = array([1,2])
I want a - b = [3,5]

Well, the equivalence of setdiff in matlab...

I thought a.difference(b) could work, but no : AttributeError:
'numpy.ndarray' object has no attribute 'difference'

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


regular expression

2009-08-20 Thread Pierre
Hello,

I would like to change the string "(1 and (2 or 3))"  by  "(x[1] & (x
[2] || x[3]))" using regular expression...
Anyone can help me ?

Thanks.



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


matplotlib / backend

2009-08-25 Thread Pierre
Hello,

I'm to plot some results but it doesn't work.
I got this error :

/usr/local/libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site-
packages/matplotlib/backends/__init__.py:41: UserWarning:
Your currently selected backend, 'agg' does not support show().
Please select a GUI backend in your matplotlibrc file ('/usr/local/
libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site-packages/
matplotlib/mpldata/matplotlibrc')
or with matplotlib.use()

Any idea to fix it ?

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


quantiles of a student distribution

2009-08-30 Thread Pierre

Hello...

Do you know how I can calculate the quantiles of a student
distribution in pyhton ?

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


lambda functions

2009-08-31 Thread Pierre
Hello,

I would like to know if it is possible to define a loop in a lambda
function

How to manage the indents ? Example :
s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s
[index]-1


Thanks !

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


rcond in numpy :

2009-08-31 Thread Pierre

Hello,

Anyone knows the numpy equivalent of the matlab function : rcond
(Matrix reciprocal condition number estimate) ?

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


hanning python

2009-09-08 Thread Pierre
Hello,

anyone knows what is the python equivalent of the matlab's hanning
function.

Note that in matlab hann and hanning are different.

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


Re: Configuraion to run pyhton script on ubuntu 12.04

2013-07-28 Thread Pierre Jaury
Jaiky  writes:

> want to run a python script which contains simple form of html on firefox 
> browser ,  but dont know what should be the configuration on ubuntu 12.04  to 
> run this script  i.e cgi configuration 
>
>
>
> My code is 
> ubder 
> in /var/www/cgi-bin/forms__.py
>
>
>
> #!/usr/bin/env python
> import webapp2
>
> form ="""
>   
> 
> 
>   """
>
>
> class MainPage(webapp2.RequestHandler):
> def get(self):
> #self.response.headers['Content-Type'] = 'text/plain'
> self.response.out.write(form)
>
> app = webapp2.WSGIApplication([('/', MainPage)],
>  debug=True)

In order for you app to run as cgi, you would have to call the webapp2
run() function. Otherwise, it is going to implement wsgi interfaces.

Have a look at:
http://webapp-improved.appspot.com/api/webapp2.html#webapp2.WSGIApplication.run

As well as:
http://httpd.apache.org/docs/current/mod/mod_alias.html#scriptalias


pgpfL_98rpm90.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Using dict as object

2012-09-19 Thread Pierre Tardy
One thing that is cooler with java-script than in python is that dictionaries 
and objects are the same thing. It allows browsing of complex hierarchical data 
syntactically easy.

For manipulating complex jsonable data, one will always prefer writing:
buildrequest.properties.myprop
rather than
brdict['properties']['myprop']

This ability in JS is well known for its flaws (e.g. 
http://drupal.org/node/172169#forin ), and I understand why this is not a 
feature that we want in python by default. I did work on class that adds this 
feature, and that I wish to use for manipulating my json data.

The following github pull request to buildbot has tests that defines 
specification of such a class, and has several commits, which gives several 
implementation of the same thing.
https://github.com/buildbot/buildbot/pull/525

All implementation I tried are much slower than a pure native dict access. 
Each implementation have bench results in commit comment. All of them are 20+x 
slower than plain dict!
I would like to have python guys advices on how one could optimize this.

I'd like to eventually post this to python-dev, please tell if this is really 
not a good idea.

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


Re: Using dict as object

2012-09-19 Thread Pierre Tardy
>
>  This has been proposed and discussed and even implemented many
> times on this list and others.
>
I can find this question on SO
http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python
which is basically answered with this solution

class AttributeDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__


but this does not allow recursive access, you would need to first convert
all nested dictionaries to AttributeDict.
a.b.c.d = 2 # fail
a.b = dict(c=3)
a.b.c=4 # fail

> I would like to have python guys advices on how one could optimize this.
>
> Use C code and slots.
>
I tried adding __slots__= [], to my class, but my benchmarks do not show
significant changes.


if you're proposing a new module for the stdlib, one of the (unstated?)
> requirements is that it be in regular use by a fairly large audience for
> a while.
>
I was talking about escalading to python-dev as a way to hit more
expertize, but it looks like this one is already
-- 
http://mail.python.org/mailman/listinfo/python-list


Brython - Python in the browser

2012-12-19 Thread Pierre Quentel
Hi,

The objective of Brython is to replace Javascript by Python as the scripting 
language for web browsers, making it usable on all terminals including 
smartphones, tablets, connected TVs, etc. Please forgive the lack of ambition 
;-)

The best introduction is to visit the Brython site (http://www.brython.info). 
Right click on the page with a clock and take a look at the source code : no 
Javascript, only Python code inside a tag 

Re: Brython - Python in the browser

2012-12-20 Thread Pierre Quentel
Le jeudi 20 décembre 2012 01:07:15 UTC+1, Terry Reedy a écrit :
> On 12/19/2012 1:19 PM, Pierre Quentel wrote:
> 
> 
> 
> > The objective of Brython is to replace Javascript by Python as the
> 
> > scripting language for web browsers, making it usable on all
> 
> > terminals including smartphones, tablets, connected TVs, etc. Please
> 
> > forgive the lack of ambition ;-)
> 
> 
> 
> This sounds similar to pyjs, but the latter has two big problems: a) 
> 
> personality conflicts splits among the developers; b) last I knew, it 
> 
> was stuck on Python 2.
> 
It is indeed different from pyjs : both translate Python into Javascript, but 
with Brython the translation is done on the fly by the browser, with pyjs is is 
done once by a Python script
> 
> 
> I think your home page/doc/announcement should specify Python 3 at the 
> 
> top, so it is not a mystery until one reads down to
> 
> "Brython supports most keywords and functions of Python 3 : "
> 
Done on the home page
> 
> 
> "lists are created with [] or list(), tuples with () or tuple(), 
> 
> dictionaries with {} or dict() and sets with set()"
> 
> 
> 
> non-empty sets are also created with {} and you should support that.
> 
Ok, I put this point in the issue tracker
> 
> 
> > The best introduction is to visit the Brython site
> 
> > (http://www.brython.info).
> 
> 
> 
> That says that my browser, Firefox 17, does not support HTML5. Golly 
> 
> gee. I don't think any browser support5 all of that moving target, and 
> 
> Gecko apparently supports about as large a subset as most.
> 
> https://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28HTML5%29
> 
> It is possible the FF still does not support the particular feature 
> 
> needed for the clock, but then the page should say just that. Has the 
> 
> latest FF (17) actually been tested?
> 
I changed the error message adding "or Javascript is turned off"
> 
> 
> > To create an element, for instance an HTML anchor :
> 
> > doc <= A('Python',href="http://www.python.org";)
> 
> 
> 
> To me, that is a awful choice and I urge you to change it.
> 
> 
> 
> '<=' is not just an operator, it is a comparison operator. It normally 
> 
> return False or True. Numpy array comparison returns arrays of booleans, 
> 
> so the meaning is extended, not completely changed. People will often be 
> 
> using it with its normal mean in conditionals elsewhere, so this usage 
> 
> creates strong cognitive dissonance. Also, using an expression as a 
> 
> statement is allowed, but except in the interactive interpreter, it only 
> 
> makes sense with an expression that obviously has side-effects or could 
> 
> have side-effects (like the expression 'mylist.sort()'. It just looks 
> 
> wrong to an experienced Python programmer like me.
> 
> 
> 
> It also is unnecessary. Use '+=' or '|='. The former means just what you 
> 
> want the statement to do and the latter is at least somewhat related 
> 
> (bit or-addition) and is rarely used and is very unlikely to be used in 
> 
> code intended for a browser.
> 
> 
I'm afraid I am going to disagree. The document is a tree structure, and today 
Python doesn't have a syntax for easily manipulating trees. To add a child to a 
node, using an operator instead of a function call saves a lot of typing ; <= 
looks like a left arrow, which is a visual indication of the meaning "receive 
as child". |= doesn't have this arrow shape

+= is supported by Brython, but it means something different. <= means "add 
child" ; the addition operator + means "add brother"

For instance,

d = UL(LI('test1'))
d += UL(LI('test2'))
doc <= d

will show two unordered lists at the same level, while

d = UL(LI('test1'))
d <= UL(LI('test2'))
doc <= d

will nest the second list inside the first one

In fact, even in CPython there could be a built-in tree class that could be 
managed by a syntax such as this one
> 
> 
> 
> > It still lacks important features of Python, mostly list
> 
> > comprehensions and classes ;
> 
> 
> 
> Since Python 3 has 4 types of comprehensions, while Python 2 only has 
> 
> list comprehensions, I took this to mean that Brython was Python 2.
> 
> 
> 
> And yes, I am all in favor of being able to use a subset of Py3 instead 
> 
> of javascript. A full Python interpreter in a browser is too dangerous. 
> 
> (Actually, I think javascript is too, but that is a different issue.) 
> 
> Python translated to javascript cannot be worse than javascript. I 
> 
> presume the same would be true if the javascript step were omitted and 
> 
> Python were directly compiled to the virtual machines defined by current 
> 
> javascript engines.
> 
> 
> 
> -- 
> 
> Terry Jan Reedy

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


Re: Brython - Python in the browser

2012-12-20 Thread Pierre Quentel
Le jeudi 20 décembre 2012 01:54:44 UTC+1, Ian a écrit :
> On Wed, Dec 19, 2012 at 5:07 PM, Terry Reedy  wrote:
> 
> > That says that my browser, Firefox 17, does not support HTML5. Golly gee. I
> 
> > don't think any browser support5 all of that moving target, and Gecko
> 
> > apparently supports about as large a subset as most.
> 
> > https://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28HTML5%29
> 
> > It is possible the FF still does not support the particular feature needed
> 
> > for the clock, but then the page should say just that. Has the latest FF
> 
> > (17) actually been tested?
> 
> 
> 
> It works for me using FF 17.0.1.
> 
> 
> 
> >> To create an element, for instance an HTML anchor :
> 
> >> doc <= A('Python',href="http://www.python.org";)
> 
> >
> 
> >
> 
> > To me, that is a awful choice and I urge you to change it.
> 
> 
> 
> +1.  The DOM already has a well-established API.  The following may
> 
> require more typing:
> 
> 
> 
> link = document.createElement('a')
> 
> link.setAttribute("href", "http://www.python.org/";)
> 
> link.appendChild(document.createTextNode('Python'))
> 
> document.body.appendChild(link)
> 
> 
> 
> But it is much clearer in intent.  Since these methods map directly to
> 
> DOM methods, I know exactly what I expect them to do, and I can look
> 
> them up in the browser documentation if I have any doubts.  With the
> 
> one-liner above, I don't know exactly what that maps to in actual DOM
> 
> calls, and so I'm a lot less clear on what exactly it is supposed to
> 
> do.  I'm not even entirely certain whether it's actually equivalent to
> 
> my code above.
> 
> 
> 
> I suggest that Brython should have a "low-level" DOM API that matches
> 
> up to the actual DOM in as close to a 1:1 correspondence as possible.
> 
> Then if you want to have a higher-level API that allows whiz-bang
> 
> one-liners like the above, build it as an abstraction on top of the
> 
> low-level API and include it as an optional library.  This has the
> 
> added benefit that if the user runs into an obscure bug where the
> 
> fancy API breaks on some particular operation on some specific
> 
> browser, they will still have the option of falling back to the
> 
> low-level API to work around it.  It would also make the conversion
> 
> barrier much lower for web programmers looking to switch to Brython,
> 
> if they can continue to use the constructs that they're already
> 
> familiar with but just write them in Python instead of JavaScript.

We don't have the same point of view. Mine is to offer an alternative to 
Javascript, with the simplicity and elegance of the Python syntax, for a 
programer who wants to develop a web application and doesn't know Javascript. 
Ultimately this means that the whole DOM API would be described without any 
mention of Javascript, only with the Python API

With this idea in mind, asking Brython to have a Javascript-like low-level API 
is like asking CPython to support iteration with a low-level construct like 
"for i=0;i<10;i++" along with "for i in range(10)". The Python engine is stable 
enough that we don't have to inspect the bytecode for debugging ; similarly, 
when Brython is mature enough, you won't have to look at the generated 
Javascript code (which you can do though, eg in the console)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brython - Python in the browser

2012-12-21 Thread Pierre Quentel
> If that's your intention, then instead of coming up with something totally
> new, unpythonic and ugly, why not take the normal Python route and
> implement a subset of the ElementTree API?
> 
> Stefan
Because the tree implementation in ElementTree or other tree modules in Python 
require a lot of typing and parenthesis

To produce the HTML code

hello world

these modules require writing something like 

div = Tag('DIV')
div.appendChild(TextNode('hello '))
b = Tag('B')
b.appendChild(TextNode('world'))
div.appendChild(b)
doc.appendChild(div)

With the tree syntax proposed in Brython it would just be

doc <= DIV('hello '+B('world'))

If "pythonic" means concise and readable, which one is more pythonic ?

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


Re: Brython - Python in the browser

2012-12-21 Thread Pierre Quentel
> Pythonic also means:
> If the implementation is hard to explain, it's a bad idea.
> What, exactly, does the sum of a string and a bolded string produce?  Can you 
> explain that easily and clearly?

Yes : a+b returns the string a+str(b)

It is exactly what you get in CPython with 
>>> class B:
...   def __init__(self,value):
... self.value = value
...   def __radd__(self,other):
... return '%s%s' %(other,self.value)
...
>>> 'hello '+B('world')
'hello world'

> The DOM structure is, undeniably, quite verbose. But you could go for
> something with the same tree structure while a lot less wordy by
> simply returning self from lots of methods, thus allowing method
> chaining - something like this:
> 
> https://github.com/Rosuav/Gypsum/blob/master/window.pike#L247
> 
Hang me if I understand what this code is supposed to do ;-)
> 
> To produce the HTML code
> 
> hello world
> 
> you might use:
> 
> doc.add(Tag('DIV').add('hello ').add(Tag('B').add('world')))
> 
No, with this syntax, the result of Tag('B').add('world') is below 'hello' in 
the tree structure, not at the same level (just below Tag('DIV')) as it should 
be

In this case it's not a real problem, but it's obvious if you want to produce 
onetwo : you would need 2 different 'add'
top = Tag('UL')
top.add(Tag('LI').add('one'))
top.add(Tag('LI').add('two'))

With the syntax used in Brython : UL(LI('one')+LI('two'))


> 
> Reject the idea if you will, but do at least please consider it :)
> 
I did in fact consider many options before proposing this one. I have done a 
lot of web programming, including a web framework, and I faced the problem of 
generating HTML code from Python. I started with a syntax with nested 
parenthesis and chained methods returning self, only ending in ugly, unreadable 
code. Once I started using <= for "add child" and "+" for "add brother" (I 
first proposed it in the Python Cookbook recipe #366000, the HTMLTags module) - 
and I've used it on fairly large projects - the result was a much cleaner code
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brython - Python in the browser

2012-12-21 Thread Pierre Quentel
> <= is a comparison expression operator, which is completely different. 
> It is just wrong for this usage. I am 99.9% sure you will come to regret 
> it eventually. Better to make the change now than in Brython2 or Brython3.

I am 99.99% sure of the contrary, having used this syntax for more than 3 years 
now, as the users of the Karrigell framework with the HTMLTags module

Another point why there is no possible confusion is that when <= is a 
comparison operator, it is never used in an standalone expression like "a <= 
b", with the left term of the comparison starting the line ; it is always used 
in an expression like "if x <= 10", "while x <= 5", "assert x <= 0", "return 
foo <= bar" etc.

So when you see a line like

doc <= DIV('hello')

it should be obvious that you are not *comparing* doc and DIV('hello'), because 
if it was the case, the line would do nothing
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brython - Python in the browser

2012-12-21 Thread Pierre Quentel

> Hmm. So when that gets added into a DIV, it has to get parsed for
> tags? How does this work? This seems very odd. I would have expected
> it to remain as DOM objects.

In DIV(child) :
- if child is a string, integer or float, a text node is added (addChild) to 
the DIV element, with the string value of child
- if child is another DOM element (as in DIV(B('foo'))) then this element is 
added to the DIV element

The code is in module py_dom.js, class $TagClass

> 
> What happens if I do, for instance:
> 'blah blah x 
You can test this code in the console on the Brython site 
(http://brython.info/tests/console_fr.html) :

doc <= 'blah blah xhttp://mail.python.org/mailman/listinfo/python-list


Re: Brython - Python in the browser

2012-12-21 Thread Pierre Quentel
> The interpreter, though, will be more than happy to treat that as a
> comparison if the LHS is not the type that you think it is.  For
> example, maybe you've added it to a string at some point, and now it's
> a string instead of an element.  I guess that since doc is made a
> keyword, that probably couldn't happen in this example, but it could
> happen when trying to add child nodes to other nodes.

Unsurprisingly, the translation engine in Brython transforms x <= y into 
x.__le__(y)

If x is a string, then __le__ means of course "lesser or equal" so y can only 
be a string, otherwise an exception is raised ; this is similar to trying to 
add a child node to a text node in the DOM

> By the way, what is Brython actually doing when you append a child to
> the document itself like that?  Usually I would expect a div to be
> appended to the body or to another div.  The above looks like it would
> attach the new div as a sibling of the html element.  Or is it just
> calling document.write()?

dom_elt <= obj actually adds one or several DOM nodes (it depends of the class 
of obj) to the DOM node represented by dom_elt. It's difficult to explain all 
the cases here, you would have to take a look at the code in py_dom.js, but <= 
and + work on the DOM tree, there is no document.write anywhere
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brython - Python in the browser

2012-12-22 Thread Pierre Quentel
> Oh, and repr is just a synonym of str, which makes it useless.
3 days ago repr was not even implemented at all, so it's a step forward...

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


Re: Brython - Python in the browser

2012-12-22 Thread Pierre Quentel
I was over-simplifying - or, to put is less diplomatically, I screwed up - when 
I answered that the addition returned a string. As Chris pointed out, it made 
the explanation very confusing. My apologies

The objects handled by + and <= can be :
- strings, integers, floats
- instances of $TagClass instances (more precisely, of classes copied from 
$TagClass, one for each HTML tag) : they are wrappers around a DOM element. The 
DOM element itself is the attribute "elt" of the $TagClass instance
- the document, represented by the keyword doc. Its attribute "elt" is the 
document (top of the DOM tree)
- instances of $AbstractClass, a container with a list of DOM elements. This 
list is the attribute "children" of the $TagClass instance


Depending of the objects types, a+b returns the following objects :

string + string : string (!)
string + $TagClass : $AbstractTag with children [textNode(a),b.elt]
string + $AbstractTag : $AbstractTag with [textNode(b)]+ b.children

The 2 latter are implemented by the method __radd__ of $TagClass and 
$AbstractTag, invoqued by the method __add__ of the string class

$TagClass + string : $AbstractTag with [a.elt,textNode(b)]
$TagClass + $TagClass : $AbstractTag with [a.elt,b.elt]
$TagClass + $AbstractTag : $AbstractTag with [a.elt]+b.children
$AbstractTag + string : $AbstractTag with a.children+[textNode(b)]
$AbstractTag + $TagClass : $AbstractTag with a.children + [b.elt]
$AbstractTag + $AbstractTag : $AbstractTag with a.children + b.children

(any type) + doc : unsupported
doc + (any type) : unsupported

The operation x <= y does the following :

string <= (any object) : comparison, if possible

($TagClass | doc) <= string | integer | float : adds textNode(str(y)) to x.elt
($TagClass | doc) <= $TagClass : adds child y.elt to parent x.elt
($TagClass | doc) <= $AbstractTag : adds DOM elements in y.children to x.elt

$AbstractClass <= (any type) : unsupported

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


Re: Brython - Python in the browser

2012-12-22 Thread Pierre Quentel
> Still, it tends to be a lot harder to explain, document, and read
> documentation for, something that uses operators weirdly, rather than
> keyword-searchable method names.

You don't explain how to use the Python syntax (for instance the operator %, 
which behaves very differently between integers and strings) by explaining what 
happens in the underlying C code in the different cases, do you ?

I would put the above explanations in the "implementation notes" of Brython, 
but not on the "how to use Brython" documentation, which is quite simple to 
explain with <= and + (it's in the section "Handling of HTML documents" in the 
docs)

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


Re: Brython - Python in the browser

2012-12-22 Thread Pierre Quentel
I forgot to mention : list comprehensions and the ternary operator (r1 if cond 
else r2) are now supported !
- Pierre
-- 
http://mail.python.org/mailman/listinfo/python-list


__doc__+= """Detailed description"""

2012-05-09 Thread Pierre Asselin
Hi.  Started using python a few months back, still settling on my style.
I write docstrings and I use "pydoc mymodule" to refresh my memory.

Problem:  if I just docstring my classes/methods/functions the
output of pydoc more or less works as a reference manual, but if
I get sidetracked for even a few weeks I find that documentation
inadequate when I return to my code.  I need to see some introductory
context first, so that the reference material makes sense.

Wery well, write a module docstring then.  The problem now: the
many paragraphs of detailed description at the top of the module
get in the way.  The pydoc output is good, but the code becomes
hard to read.

So I come up with this:

##
#! env python

"""One-liner docstring."""

# Many classes, methods, functions, attributes,
# with docstrings as needed.  Docs tend to be
# short and the code speaks for itself.
# ...
# Much further down,

___doc___+= """

Detailed description goes here.  Provide some context,
explain what the classes are for and what the most important
methods are, give simple examples, whatever.  Say enough
to make the rest understandable."""

if __name__ == "__main__":
# test code follows
##

It seems to work, too.  But is that a sound way to write python?
Am I relying on undocumented implementation details or am I safe?

I guess I am trying to control the order of exposition without
resorting to full-fledged Literate Programming.


-- 
pa at panix dot com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Crazy what-if idea for function/method calling syntax

2011-07-18 Thread Pierre Quentel
On 18 juil, 07:54, Steven D'Aprano  wrote:
> On Mon, 18 Jul 2011 08:54 am ΤΖΩΤΖΙΟΥ wrote:
>
> > Jumping in:
>
> > What if a construct
>
> >    xx(*args1, **kwargs1)yy(*args2, **kwargs2)
>
> > was interpreted as
>
> >   xxyy(*(args1+args2), **(kwargs1+kwargs2))
>
> > (Note: with **(kwargs1+kwargs2) I mean “put keyword arguments in the
> > order given”, since dicts can't be added)
>
> > This construct is currently a syntax error. The intent of this idea is
> > to help improve legibility.
>
> I don't think it does that. I think it is misleading, as it looks like two
> independent function calls. It also makes it hard to search for a function
> call -- instead of searching for
>
> do_something\(.*\)
>
> you have to now search for
>
> do_something\(.*\)
> do\(.*\)_something\(.*\)
> do_\(.*\)something\(.*\)
> do_some\(.*\)thing\(.*\)
>
> and so on.
>
> > Example:
> >   def place_at(item, x, y): blah blah
> > could be called as
> >   place(item)_at(x, y)
>
> You would probably like the Xtalk family of languages, starting with
> Hypertalk from Apple in the late 80s or early 90s.
>
> There's a neat implementation here:http://code.google.com/p/openxion/
>
> Xtalk includes syntax like this:
>
> put newStr into character 23 to 42 of theStr
> put suffix after theStr
> delete first char of theStr
>
> although this only applied to built-in functions, not user-functions.
>
> --
> Steven

If I understand correctly, you propose to translate "do something to X
with arguments a,b,c" to

(1) do_something_to(X)_with_arguments(a,b,c)

instead of

(2) do_something(X,a,b,c)

I agree that the first one is more readable than the second, because
in the arguments list in (2) you mix the object you are working on and
the parameters used. But there is another option :

(3) X.do_something_with_arguments(a,b,c)

which would be in your examples : "item.place_at(x,y)" or
"iterable.group_by(collection)"

It's valid Python code and probably as readable than what you suggest,
with a clear distinction between the object and the arguments

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


Relative seeks on string IO

2011-09-06 Thread Pierre Quentel
Hi,

I am wondering why relative seeks fail on string IO in Python 3.2

Example :

from io import StringIO
txt = StringIO('Favourite Worst Nightmare')
txt.seek(8) # no problem with absolute seek

but

txt.seek(2,1) # 2 characters from current position

raises "IOError: Can't do nonzero cur-relative seeks" (tested with
Python3.2.2 on WindowsXP)

A seek relative to the end of the string IO raises the same IOError

However, it is not difficult to simulate a class that performs
relative seeks on strings :


class FakeIO:

def __init__(self,value):
self.value = value
self.pos = 0

def read(self,nb=None):
if nb is None:
return self.value[self.pos:]
else:
return self.value[self.pos:self.pos+nb]

def seek(self,offset,whence=0):
if whence==0:
self.pos = offset
elif whence==1: # relative to current position
self.pos += offset
elif whence==2: # relative to end of string
self.pos = len(self.value)+offset

txt = FakeIO('Favourite Worst Nightmare')
txt.seek(8)
txt.seek(2,1)
txt.seek(-8,2)
=

Is there any reason why relative seeks on string IO are not allowed in
Python3.2, or is it a bug that could be fixed in a next version ?

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


Re: Relative seeks on string IO

2011-09-07 Thread Pierre Quentel
>
> Please post code without non-code indents, like so:
>
Sorry about that. After the line "Example :" I indented the next
block, out of habit ;-)
>
> What system are you using? Does it have a narrow or wide unicode build?
> (IE, what is the value of sys.maxunicode?)
>
I use Windows XP Pro, version 2002, SP3. sys.maxunicode is 65535

I have the same behaviour with 3.1.1 and with 2.7

I don't understand why variable sized code units would cause problems.
On text file objects, read(nb) reads nb characters, regardless of the
number of bytes used to encode them, and tell() returns a position in
the text stream just after the next (unicode) character read

As for SringIO, a wrapper around file objects simulates a correct
behaviour for relative seeks :


txt = "abcdef"
txt += "تخصيص هذه الطبعة"
txt += "머니투데이"
txt += "endof file"

out = open("test.txt","w",encoding="utf-8")
out.write(txt)
out.close()

fobj = open("test.txt",encoding="utf-8")
fobj.seek(3)
try:
fobj.seek(2,1)
except IOError:
print('raises IOError')

class _file:

def __init__(self,file_obj):
self.file_obj = file_obj

def read(self,nb=None):
if nb is None:
return self.file_obj.read()
else:
return self.file_obj.read(nb)

def seek(self,offset,whence=0):
if whence==0:
self.file_obj.seek(offset)
else:
if whence==2:
# read till EOF
while True:
buf = self.file_obj.read()
if not buf:
break
self.file_obj.seek(self.file_obj.tell()+offset)

fobj = _file(open("test.txt",encoding="utf-8"))
fobj.seek(3)
fobj.seek(2,1)
fobj.seek(-5,2)
print(fobj.read(3))
==

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


Trapping the segfault of a subprocess.Popen

2011-04-06 Thread Pierre GM
All,

I need to run a third-party binary from a python script and retrieve
its output (and its error messages). I use something like
>>> process = subprocess.Popen(options, stdout=subprocess.PIPE, 
>>> stderr=subprocess.PIPE)
>>> (info_out, info_err) = process.communicate()
That works fine, except that the third-party binary in question
doesn't behave very nicely and tend to segfaults without returning any
error. In that case, `process.communicate` hangs for ever.

I thought about calling a `threading.Timer` that would call
`process.terminate` if `process.wait` doesn't return after a given
time... But it's not really a solution: the process in question can
sometimes take a long time to run, and I wouldn't want to kill a
process still running.
I also thought about polling every x s and stopping when the result of
a subprocess.Popen(["ps","-p",str(initialprocess.pid)],
stdout=subprocess.PIPE) becomes only the header line, but my script
needs to run on Windows as well (and no ps over there)...

Any suggestion welcome,
Thx in advance
P.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trapping the segfault of a subprocess.Popen

2011-04-07 Thread Pierre GM
On Apr 7, 1:58 am, Nobody  wrote:
> On Wed, 06 Apr 2011 02:20:22 -0700, Pierre GM wrote:
> > I need to run a third-party binary from a python script and retrieve
> > its output (and its error messages). I use something like
> >>>> process = subprocess.Popen(options, stdout=subprocess.PIPE,
> > stderr=subprocess.PIPE)
> >>>> (info_out, info_err) = process.communicate()
> > That works fine, except that the third-party binary in question doesn't
> > behave very nicely and tend to segfaults without returning any error. In
> > that case, `process.communicate` hangs for ever.
>
> Odd. The .communicate method should return once both stdout and stderr
> report EOF and the process is no longer running. Whether it terminates
> normally or on a signal makes no difference.
>
> The only thing I can think of which would cause the situation which you
> describe is if the child process spawns a child of its own before
> terminating. In that case, stdout/stderr won't report EOF until any
> processes which inherited them have terminated.

I think you nailed it. Running the incriminating command line in a
terminal doesn't return to the prompt. In fact, a ps shows that the
process is sleeping in the foreground. Guess I should change the
subject of this thread...



> > I thought about calling a `threading.Timer` that would call
> > `process.terminate` if `process.wait` doesn't return after a given
> > time... But it's not really a solution: the process in question can
> > sometimes take a long time to run, and I wouldn't want to kill a
> > process still running.
> > I also thought about polling every x s and stopping when the result of
> > a subprocess.Popen(["ps","-p",str(initialprocess.pid)],
> > stdout=subprocess.PIPE) becomes only the header line, but my script
> > needs to run on Windows as well (and no ps over there)...
>
> It should suffice to call .poll() on the process. In case that doesn't
> work, the usual alternative would be to send signal 0 to the process (this
> will fail with ESRCH if the process doesn't exist and do nothing
> otherwise), e.g.:
>
> import os
> import errno
>
> def exists(process):
>     try:
>         os.kill(process.pid, 0)
>     except OSError, e:
>         if e.errno == errno.ESRCH:
>             return False
>         raise
>     return True

OK, gonna try that, thx.


> You might need to take a different approach for Windows, but the above is
> preferable to trying to parse "ps" output. Note that this only tells you
> if /some/ process exists with the given PID, not whether the original
> process exists; that information can only be obtained from the Popen
> object.

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


Re: Trapping the segfault of a subprocess.Popen

2011-04-07 Thread Pierre GM
On Apr 7, 5:12 am, Terry Reedy  wrote:
> On 4/6/2011 7:58 PM, Nobody wrote:
>
> > On Wed, 06 Apr 2011 02:20:22 -0700, Pierre GM wrote:
>
> >> I need to run a third-party binary from a python script and retrieve
> >> its output (and its error messages). I use something like
> >>>>> process = subprocess.Popen(options, stdout=subprocess.PIPE,
> >> stderr=subprocess.PIPE)
> >>>>> (info_out, info_err) = process.communicate()
> >> That works fine, except that the third-party binary in question doesn't
> >> behave very nicely and tend to segfaults without returning any error. In
> >> that case, `process.communicate` hangs for ever.
>
> I am not sure this will help you now, but
> Victor Stinner has added a new module to Python 3.3 that tries to catch
> segfaults and other fatal signals and produce a traceback before Python
> disappears.

Unfortunately, I'm limited to Python 2.5.x for this project. But good
to know, thanks...

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


Re: how to setup for localhost:8000

2016-04-15 Thread Pierre Quentel
Le jeudi 14 avril 2016 22:50:33 UTC+2, wrh...@gmail.com a écrit :
> On Thursday, April 14, 2016 at 2:23:36 PM UTC-4, Andrew Farrell wrote:
> > What happens when you type
> > 
> > http://localhost:8000
> > 
> > Into the address bar of your browser as this is running?
> > 
> > On Thu, Apr 14, 2016 at 12:46 PM,  wrote:
> > 
> > > Hi,
> > >
> > > I am working on window 7 and Python 3.5 to setup a localhost:8000 but it
> > > did not get through as shown below:
> > > > python -m http.server
> > > Serving HTTP on 0.0.0.0 port 8000 ...
> > >
> > > But it did not show the results.
> > >
> > > Can someone help me how to setup the localhost?
> > >
> > > Thanks,
> > > Wen-Ruey
> > >
> > > --
> > > https://mail.python.org/mailman/listinfo/python-list
> > >
> 
> hi Andrew,
> 
> Yes. after I type http:\\localhost:8000, the browser did not show anything 
> except a empty page without any errors.
> 
> Thanks,
> Wen-Ruey

Hi,

When you type http://localhost:8000, do you see something in the console after 
the line  "Serving HTTP on 0.0.0.0 port 8000 ..." ?

If the server actually serves requests on port 8000 you should see a log 
message such as

127.0.0.1 - - [15/Apr/2016 20:57:32] "GET / HTTP/1.1" 200 -
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to setup for localhost:8000

2016-04-17 Thread Pierre Quentel

> > 127.0.0.1 - - [15/Apr/2016 20:57:32] "GET / HTTP/1.1" 200 -
>  Hi Pierre,
> 
> When I type http://localhost:8000, I did not see anything in the console 
> after the line "Serving HTTP on 0.0.0.0 port 8000 ... I believe the way I ran 
> was not correct as shown below:
> > python -m http.server 
> Serving HTTP on 0.0.0.0 port 8000 ...
> 
> Also if I use internet Explorer, it shows HTTP 404 errors.
> Do you think the way I am doing of the localhost:8000 setting was not correct?
> 
> Thanks,
> Wen-Ruey

If you're not seeing anything there, it is sure that the Python server doesn't 
serve requests on port 8000. But if you're seeing a blank screen or a 404 error 
instead of a message saying that a connection couldn't be set up, it is likely 
that another HTTP server is running on your machine on port 8000.

Could you try to start the server on another port, eg "python -m http.server 
8085" and see what happens in the browser with "http://127.0.0.1:8085"; ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: do_POST not working on http.server with python

2016-05-01 Thread Pierre Quentel
Le jeudi 28 avril 2016 10:36:27 UTC+2, Rahul Raghunath a écrit :
> 0
> down vote
> favorite
>   
> 
> I'm trying to create a simple http server with basic GET and POST 
> functionality. The program is supposed to GET requests by printing out a 
> simple webpage that greets a user and askes how he would rather be greeted. 
> When the user enters a greeting of his choice, the webpage should now greet 
> him as he had chosen.
> 
> While GET seems to be working fine, POST is not. I tried debugging by 
> printing at every code execution and it seems to be getting stuck here:
> 
> ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
> 
> I'll paste the code full code below, along with my terminal output.
> 
> Code:
> 
> from http.server import BaseHTTPRequestHandler, HTTPServer
> import cgi
> 
> 
> class webServerHandler(BaseHTTPRequestHandler):
> 
> def do_GET(self):
> try:
> if self.path.endswith("/hello"):
> self.send_response(200)
> self.send_header('Content-type', 'text/html')
> self.end_headers()
> output = ""
> output += ""
> output += "Hello!"
> output += ''' enctype='multipart/form-data' action='/hello'>What would you like me to 
> say? value="Submit"> '''
> output += ""
> self.wfile.write(output.encode(encoding = 'utf_8'))
> print (output)
> return
> 
> if self.path.endswith("/hola"):
> self.send_response(200)
> self.send_header('Content-type', 'text/html')
> self.end_headers()
> output = ""
> output += ""
> output += "¡ Hola !"
> output += ''' enctype='multipart/form-data' action='/hello'>What would you like me to 
> say? value="Submit"> '''
> output += ""
> self.wfile.write(output.encode(encoding = 'utf_8'))
> print (output)
> return
> 
> except IOError:
> self.send_error(404, 'File Not Found: %s' % self.path)
> 
> def do_POST(self):
> try:
> self.send_response(201)
> print("Sent response")
> self.send_header('Content-type', 'text/html')
> print("Sent headers")
> self.end_headers()
> print("Ended header")
> ctype, pdict = 
> cgi.parse_header(self.headers.getheader('content-type'))
> print("Parsed headers")
> if ctype == 'multipart/form-data':
> fields = cgi.parse_multipart(self.rfile, pdict)
> messagecontent = fields.get('message')
> print("Receiver message content")
> output = ""
> output += ""
> output += "  Okay, how about this: "
> output += " %s " % messagecontent[0]
> output += ''' enctype='multipart/form-data' action='/hello'>What would you like me to 
> say? value="Submit"> '''
> output += ""
> print(output)
> self.wfile.write(output.encode(encoding = 'utf_8'))
> print ("Wrote through CGI")
> except:
> pass
> 
> 
> def main():
> try:
> port = 8080
> server = HTTPServer(('', port), webServerHandler)
> print ("Web Server running on port", port)
> server.serve_forever()
> except KeyboardInterrupt:
> print (" ^C entered, stopping web server")
> server.socket.close()
> 
> if __name__ == '__main__':
> main()
> 
> Terminal Output:
> 
> Web Server running on port 8080
> 127.0.0.1 - - [28/Apr/2016 13:28:59] "GET /hello HTTP/1.1" 200 -
> Hello! enctype='multipart/form-data' action='/hello'>What would you like me to 
> say? value="Submit"> 
> 127.0.0.1 - - [28/Apr/2016 13:29:09] "POST /hello HTTP/1.1" 201 -
> Sent response
> Sent headers
> Ended header
> 
> As you can see, the POST function does not seem to go beyong the parse_header 
> command. I cannot figure this out, and any help would be usefu!

Hi,

It's generally not considered good practise to silently ignore exceptions in a 
try/except where the except clause is just :

except:
   pass

If you remove the try/except in do_POST you will see this interesting error 
message :

AttributeError: 'HTTPMessage' object has no attribute 'getheader'
-- 
https://mail.python.org/mailman/listinfo/python-list


Generator question

2019-03-13 Thread Pierre Reinbold
Dear all,

I want to implement a function computing the Cartesian product if the elements
of a list of lists, but using generator expressions. I know that it is already
available in itertools but it is for the sake of understanding how things work.

I already have a working recursive version, and I'm quite sure that this
iterative version used to work (at least in some Python2.X) :

def flat_genexp_cat_prod(lists):
solutions = [[]]
for a_list in lists:
solutions = (part_sol+[el] for part_sol in solutions for el in a_list)
return solutions

But, with Python3.7.2, all I got is this :

>>> list(flat_genexp_cat_prod([[1, 2], [3, 4], [5, 6]]))
[[5, 5, 5], [5, 5, 6], [5, 6, 5], [5, 6, 6], [6, 5, 5], [6, 5, 6], [6, 6, 5],
[6, 6, 6]]

instead of

>>> list(flat_genexp_cat_prod([[1, 2], [3, 4], [5, 6]]))
[[1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5],
[2, 4, 6]]

Using a list comprehension instead of a generator expression solves the problem,
but I can't understand why the version above fails.

Even stranger, when debugging I tried to use itertools.tee to duplicate the
solutions generators and have a look at them :

def flat_genexp_cat_prod(lists):
solutions = [[]]
for a_list in lists:
solutions, debug = tee(
part_sol+[el] for part_sol in solutions for el in a_list)
print("DEBUG", list(debug))
return solutions

And, that version seems to work!

>>> list(flat_genexp_cat_prod([[1, 2], [3, 4], [5, 6]]))
DEBUG [[1], [2]]
DEBUG [[1, 3], [1, 4], [2, 3], [2, 4]]
DEBUG [[1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4,
5], [2, 4, 6]]
[[1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5],
[2, 4, 6]]

Can you help me understand what I'm doing wrong ?

Thank you by advance,


πr
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generator question

2019-03-14 Thread Pierre Reinbold
Wow, thank you Ian for this very detailed answer, and thank you for taking the
time for that! Much appreciated!

If I get this right, I have to somehow fix the value of a_list during the loop,
like when you use the classic default value argument trick with lambdas (damn, I
should have thought of that!). So if I "unfold" the generator expression, using
default values for both iterables, I get this :

def flat_gen_cat_prod(lists):
solutions = [[]]
for a_list in lists:
def new_solutions(l=a_list, s=solutions):
for part_sol in s:
for el in l:
yield part_sol+[el]
solutions = new_solutions()
return solutions

With this I get the right behavior! Thanks again!

Doest that mean that there is no possibility to use a generator expression in
this case ? (gen. exp. are sooo much more elegant :-))

Thanks again for the answer and helpful comments!


πr

Le 14/03/19 à 02:44, Ian Kelly a écrit :
> You're basically running into this:
> https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
> 
> To see why, let's try disassembling your function. I'm using Python 3.5
> here, but it shouldn't make much of a difference.
> 
> py> import dis
> py> dis.dis(flat_genexp_cat_prod)
>   2   0 BUILD_LIST   0
>   3 BUILD_LIST   1
>   6 STORE_FAST   1 (solutions)
> 
>   3   9 SETUP_LOOP  39 (to 51)
>  12 LOAD_FAST0 (lists)
>  15 GET_ITER
> >>   16 FOR_ITER31 (to 50)
>  19 STORE_DEREF  0 (a_list)
> 
>   4  22 LOAD_CLOSURE 0 (a_list)
>  25 BUILD_TUPLE  1
>  28 LOAD_CONST   1 ( at
> 0x73f31571ac90, file "", line 4>)
>  31 LOAD_CONST   2
> ('flat_genexp_cat_prod..')
>  34 MAKE_CLOSURE 0
>  37 LOAD_FAST1 (solutions)
>  40 GET_ITER
>  41 CALL_FUNCTION1 (1 positional, 0 keyword pair)
>  44 STORE_FAST   1 (solutions)
>  47 JUMP_ABSOLUTE   16
> >>   50 POP_BLOCK
> 
>   5 >>   51 LOAD_FAST1 (solutions)
>  54 RETURN_VALUE
> 
> Now, take a look at the difference between the instruction at address 22
> and the one at address 37:
> 
>   4  22 LOAD_CLOSURE 0 (a_list)
>  37 LOAD_FAST1 (solutions)
> 
> The value of solutions is passed directly to the generator as an argument,
> which is the reason why building the generator up iteratively like this
> works at all: although the nested generators are evaluated lazily, each new
> generator that is constructed contains as its input a reference to the
> previous generator.
> 
> By contrast, the value of a_list is a closure. The contents of the closure
> are just whatever the value of a_list is when the generator gets evaluated,
> not when the generator was created. Since the entire nested generated
> structure is evaluated lazily, it doesn't get evaluated until list() is
> called after the function has returned. The value of the a_list closure at
> that point is the last value that was assigned to it: the list [5, 6] from
> the last iteration of the for loop. This same list value then gets used for
> all three nested generators.
> 
> So now why do solutions and a_list get treated differently like this? To
> answer this, look at this paragraph about generator expressions from the
> language reference:
> 
> """
> Variables used in the generator expression are evaluated lazily when the
> __next__() method is called for the generator object (in the same fashion
> as normal generators). However, the iterable expression in the leftmost for
> clause is immediately evaluated, so that an error produced by it will be
> emitted at the point where the generator expression is defined, rather than
> at the point where the first value is retrieved. Subsequent for clauses and
> any filter condition in the leftmost for clause cannot be evaluated in the
> enclosing scope as they may depend on the values obtained from the leftmost
> iterable. For example: (x*y for x in range(10) for y in range(x, x+10)).
> """
> 
> So, it's simply because the iterable expression in the leftmost for clause
> is treated differently from every other value in the generator expression.
> 
> On Wed, Mar 13, 2019 at 3:49 PM Pierre Reinbold  wrote:
> 
>> Dear all,
>>
>

Re: Generator question

2019-03-14 Thread Pierre Reinbold
Le 14/03/19 à 10:45, Peter Otten a écrit :
> Pierre Reinbold wrote:
> 
>> Wow, thank you Ian for this very detailed answer, and thank you for taking
>> the time for that! Much appreciated!
>>
>> If I get this right, I have to somehow fix the value of a_list during the
>> loop, like when you use the classic default value argument trick with
>> lambdas (damn, I should have thought of that!). So if I "unfold" the
>> generator expression, using default values for both iterables, I get this
>> :
>>
>> def flat_gen_cat_prod(lists):
>> solutions = [[]]
>> for a_list in lists:
>> def new_solutions(l=a_list, s=solutions):
>> for part_sol in s:
>> for el in l:
>> yield part_sol+[el]
>> solutions = new_solutions()
>> return solutions
>>
>> With this I get the right behavior! Thanks again!
>>
>> Doest that mean that there is no possibility to use a generator expression
>> in this case ? (gen. exp. are sooo much more elegant :-))
> 
> The obvious approach is to put the genexpr into a function:
> 
> def prod(lists):
> solutions = [[]]
> def new_solutions(a_list):
> return (part_sol + [el] for part_sol in solutions for el in a_list)
> 
> for a_list in lists:
> solutions = new_solutions(a_list)
> return solutions
> 
> If you want to avoid the function you can take advantage of the fact that 
> the outermost iterable is bound early:
> 
> def prod(lists):
> solutions = [[]]
> 
> for a_list in lists:
> solutions = (
> part_sol + [el]
> for solutions, a_list in [(solutions, a_list)]
> for part_sol in solutions for el in a_list
> )
> return solutions
> 
> 

Thank you Peter, very clever suggestions !


πr
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generator question

2019-03-14 Thread Pierre Reinbold
Wow, thank you Ian for this very detailed answer, and thank you for taking the
time for that! Much appreciated!

If I get this right, I have to somehow fix the value of a_list during the loop,
like when you use the classic default value argument trick with lambdas (damn, I
should have thought of that!). So if I "unfold" the generator expression, using
default values for both iterables, I get this :

def flat_gen_cat_prod(lists):
solutions = [[]]
for a_list in lists:
def new_solutions(l=a_list, s=solutions):
for part_sol in s:
for el in l:
yield part_sol+[el]
solutions = new_solutions()
return solutions

With this I get the right behavior! Thanks again!

Doest that mean that there is no possibility to use a generator expression in
this case ? (gen. exp. are sooo much more elegant :-))

Thanks again for the answer and helpful comments!


πr

Le 14/03/19 à 02:44, Ian Kelly a écrit :
> You're basically running into this:
> https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
> 
> To see why, let's try disassembling your function. I'm using Python 3.5
> here, but it shouldn't make much of a difference.
> 
> py> import dis
> py> dis.dis(flat_genexp_cat_prod)
>   2   0 BUILD_LIST   0
>   3 BUILD_LIST   1
>   6 STORE_FAST   1 (solutions)
> 
>   3   9 SETUP_LOOP  39 (to 51)
>  12 LOAD_FAST0 (lists)
>  15 GET_ITER
> >>   16 FOR_ITER31 (to 50)
>  19 STORE_DEREF  0 (a_list)
> 
>   4  22 LOAD_CLOSURE 0 (a_list)
>  25 BUILD_TUPLE  1
>  28 LOAD_CONST   1 ( at
> 0x73f31571ac90, file "", line 4>)
>  31 LOAD_CONST   2
> ('flat_genexp_cat_prod..')
>  34 MAKE_CLOSURE 0
>  37 LOAD_FAST1 (solutions)
>  40 GET_ITER
>  41 CALL_FUNCTION1 (1 positional, 0 keyword pair)
>  44 STORE_FAST   1 (solutions)
>  47 JUMP_ABSOLUTE   16
> >>   50 POP_BLOCK
> 
>   5 >>   51 LOAD_FAST1 (solutions)
>  54 RETURN_VALUE
> 
> Now, take a look at the difference between the instruction at address 22
> and the one at address 37:
> 
>   4  22 LOAD_CLOSURE 0 (a_list)
>  37 LOAD_FAST1 (solutions)
> 
> The value of solutions is passed directly to the generator as an argument,
> which is the reason why building the generator up iteratively like this
> works at all: although the nested generators are evaluated lazily, each new
> generator that is constructed contains as its input a reference to the
> previous generator.
> 
> By contrast, the value of a_list is a closure. The contents of the closure
> are just whatever the value of a_list is when the generator gets evaluated,
> not when the generator was created. Since the entire nested generated
> structure is evaluated lazily, it doesn't get evaluated until list() is
> called after the function has returned. The value of the a_list closure at
> that point is the last value that was assigned to it: the list [5, 6] from
> the last iteration of the for loop. This same list value then gets used for
> all three nested generators.
> 
> So now why do solutions and a_list get treated differently like this? To
> answer this, look at this paragraph about generator expressions from the
> language reference:
> 
> """
> Variables used in the generator expression are evaluated lazily when the
> __next__() method is called for the generator object (in the same fashion
> as normal generators). However, the iterable expression in the leftmost for
> clause is immediately evaluated, so that an error produced by it will be
> emitted at the point where the generator expression is defined, rather than
> at the point where the first value is retrieved. Subsequent for clauses and
> any filter condition in the leftmost for clause cannot be evaluated in the
> enclosing scope as they may depend on the values obtained from the leftmost
> iterable. For example: (x*y for x in range(10) for y in range(x, x+10)).
> """
> 
> So, it's simply because the iterable expression in the leftmost for clause
> is treated differently from every other value in the generator expression.
> 
> On Wed, Mar 13, 2019 at 3:49 PM Pierre Reinbold  wrote:
> 
>> Dear all,
>>
>

tkinter and input()

2020-09-29 Thread Pierre Bonville
 Hello everybody,
I have a small problem with the method .quit() of tkinter. Below is a
sketch of a much larger program, which shows the problem. I would like to
run the main program but keeping the tk window on the screen until the end.
Presently, execution stops after the first "plot" instruction. I don't
understand why. The program runs fine if one replaces "quit" by "destroy",
but then the tk window disappears. Is there a solution?
Thanks in advance for any answer,
Regards,
P.Bonville

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from tkinter import *
def init():
global vit
def print_par():
global vitt
vitt = vit.get()
print("velocity= ",vitt," cm/s")
fen.quit()

vit = ""
fen = Tk()
vit0 = StringVar()
Label(fen, text = "velocity (cm/s): ").grid(row=0)
vit = Entry(fen,text = vit0)
vit0.set(7.)
vit.grid(row=0, column=1)
button = Button(fen, text='OK', command=print_par).grid(row=5,column=0)
fen.mainloop()

vit = float(vitt)

init()
print(vit)

x = np.arange(0,4*np.pi,0.1)
y = np.sin(x)

for i in range(0,10):
plt.plot(x,y)
plt.show()
re = input("Hit RETURN to continue:")
-- 
https://mail.python.org/mailman/listinfo/python-list


Interference tkinter and plot from matplotlib

2020-09-30 Thread Pierre Bonville
 Hi everybody,
I am running this little program below on Win 10 with Python 3.8 (just
typing prog.py after the prompt c:\Users ...>), and while it correctly
displays the window and does the first plt.plot(), it does not reach the
input command and remains waiting after I shut the plot. If I replace
'quit' by 'destroy' in the button command, it works correctly. I looked on
various Python forums on the Net, but didn't find an answer.
Regards,
P.Bonville

import tkinter as tk
import matplotlib.pyplot as plt
r = tk.Tk()
b = tk.Button(r, text= r.quit)
b = tk.Button(r, text='quit', command=r.quit)
b.pack()
r.mainloop()  # This blocks until press button.
# Root window with button is still displayed.
plt.plot()
plt.show()
rep = input("Return")
plt.plot()
plt.show()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Interference tkinter and plot from matplotlib

2020-10-01 Thread Pierre Bonville
Thank you, Mr. Gollwitzer. I understand the problem. I'll see what I can do.
Regards,
P.Bonville


Le mer. 30 sept. 2020 à 17:02, Christian Gollwitzer  a
écrit :

> Am 30.09.20 um 15:46 schrieb Pierre Bonville:
> >   Hi everybody,
>
> > Interference tkinter and plot from matplotlib
>
>
> You are mixing different ways of control flow. In a GUI program, don't
> call input(). Use the mainloop() as the very last of your calls, and
> only work in the callbacks. That means you would integrate a "Next"
> button in your GUI which switches the plots - or even show them side by
> side.
>
> Concerning matplotlib, you'll need to tell it to integrate with Tk
> properly.
>
> https://matplotlib.org/3.3.1/gallery/user_interfaces/embedding_in_tk_sgskip.html
>
>
> If you want a simple solution instead of full-blown GUI programming, use
> IPython https://ipython.readthedocs.io/en/stable/config/eventloops.html
> or jupyter notebooks.
>
>
> Christian
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: sqlstring -- a library to build a SELECT statement

2005-10-20 Thread Pierre Quentel
[EMAIL PROTECTED] a écrit :
> 
> 
> My solution is sqlstring. A single-purpose library: to create SQL
> statement objects. These objects (such as sqlstring.Select), represent
> complex SQL Statements, but as Python objects. The benefit is that you
> can, at run-time, "build" the statement pythonically, without
> getting bogged down in String Manipulation. The theory is that once in
> use, things that were complex (string magic) become simpler, and allow
> the program to worry about higher-level issues.
> 
With the same starting point - I don't like writing SQL strings inside 
Python code either - I have tested a different approach : use the Python 
list comprehension / generator expression syntax for the select requests

I have published a recipe on the Python Cookbook : 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442447

For instance :

s = query(r.name for r in planes if r.speed > 500)
for item in s:
print s

query is a class whose instances are created with the generator 
expression as argument. The matching SQL request is built in the 
__init__ method, here :

SELECT r.name FROM planes AS r WHERE r.speed > 500

On two tables :

s=query(r.name for r in planes for c in countries if r.country ==
 c.country and c.continent == 'Europe')

is translated into :

SELECT r.name FROM countries AS c ,plane AS r WHERE (r.country =
 c.country AND c.continent = 'Europe')

For the moment the implementation is not very elegant, especially for 
getting the source code of the generator expression (it would be nice if 
they had an attribute for that !), and I'm not sure if it could work for 
all the forms of the SELECT syntax. But it should cover at least the 
most usual kinds of requests, with a Pythonic syntax

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


Re: popen2

2005-10-29 Thread Pierre Hanser
Grant Edwards a écrit :
> On 2005-10-29, Piet van Oostrum <[EMAIL PROTECTED]> wrote:
> 
>>>"g.franzkowiak" <[EMAIL PROTECTED]> (gf) wrote:
>>
>>>gf> If starts a process with popen2.popen3('myprogram') and myprogram.exe is
>>>gf>  running before, I've a connection to the second process, not to the 
>>>first.
>>>gf> I can find the process by name before I start a process with popen2...,
>>>gf> but how bcan I connect t this process with a pipe ?
>>
>>You have to use a named pipe.
> 
> 
> That would require that the application know about the named
> pipe and open it.  I don't think there is any way to swap a
> pipe in for stdin/stdout once a process is running.
> 
in C: freopen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which feature of python do you like most?

2005-11-08 Thread Pierre Quentel
[EMAIL PROTECTED] a écrit :
> 
> what is the thing that python makes you happy?
> 

I discovered Python 5 years ago and I remember very well that what 
attracted me first was indentation. I had learnt JavaScript and 
rudiments of Java and couldn't decide on a consistent way of indenting 
my code, so it looked rather ugly and difficult to read. The first 
Python programs I saw struck me for the beauty of their graphical design 
(the use of lowercase letters also counts)

As a learned the language itself I was attracted for the same reasons as 
the ones already given (simplicity, built-in types, list 
comprehensions...), but I still feel the same aesthetic pleasure every 
time I open a Python program to work on it

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


Re: strip not working on strings?

2005-11-13 Thread Pierre Quentel
[EMAIL PROTECTED] a écrit :
> I'm using Python 2.3.5 and when I type the following in the interactive
> prompt I see that strip() is not working as advertised:
> 
> 
>>>>s = 'p p:p'
>>>>s.strip(' :')
> 
> 'p p:p'
> 
> Is this just me or does it not work? I want to get rid of all ' ' and
> ':' in the string. I've checked the doc and from what I can tell this
> is what strip() is supposed to do. Thanks for any help.
> 

strip(chars) "returns a copy of the string with leading and trailing 
characters removed", that is, at the beginning and at the end of the string

You can use this to remove the specified characters :

for char in chars:
 s.replace(char,'')

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


Re: Hlelp clean up clumpsy code

2005-01-04 Thread Pierre Quentel
You can also do it in a more pythonic way but without generators :
# a = [[1,5,2], 8, 4]
# l = []
# for item in a:
#if isinstance(item, (int, long)):
#l.append(item)
#else:
#l+=item
# print dict([(item,i+1) for (i,item) in enumerate(l)])
It works in the same conditions as your original code (no nested lists)
A few other things :
- you don't have to type a comma for one-item lists : x = [x] works - 
you probably confused with tuples where you must do x=(x,)
- instead of
# for w in [y for y in x]:
just do
# for w in x:
-  for "i = i+1" there is a shortcut : i+=1 (see "l+=item" above)

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


Another look at language comparisons

2005-01-08 Thread Pierre Quentel
http://khason.biz/blog/2004/12/why-microsoft-can-blow-off-with-c.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: The best way to do web apps with Python?

2005-01-08 Thread Pierre Quentel
worzel a écrit :
What is the best way to web developemnt with Python? Is there anything 
close to PHP style in-page script placement that can create and use 
other Python objects? I am not really interested in Zope (I believe that 
is more a CMS than anything else?) I am also looking for something a 
little more structured than a series of CGI Scripts.
 
There are quite a few web frameworks in Python, see 
http://www.python.org/moin/WebProgramming

I'm biaised in favour of Karrigell (http://karrigell.sourceforge.net), 
the "Python Inside HTML" pages look and behave very much like PHP

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


Comments in configuration files

2005-01-22 Thread Pierre Quentel
Bonjour,
I am developing an application and I have a configuration file with a 
lot of comments to help the application users understand what the 
options mean

I would like it to be editable, through a web browser or a GUI 
application. With ConfigParser I can read the configuration file and 
edit the options, but when I write the result all the comments are lost

Are there modules that work on the same kind of ini files (for the needs 
of my application, I prefer this format to XML or YAML) and don't remove 
the comments ?

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


pygsl-0.3.1 released

2005-01-24 Thread Pierre Schnizer
pyGSL is a wrapper for the GNU Scientific Library. Get it from
http://sourceforge.net/projects/pygsl.

Up to now it provides the following modules:
Blas, Chebyshev, Combination, Const
Diff, Deriv, Eigen, Fit, FFT, Ieee, Integrate
Interpolation, Linalg, Math
Minimize, Multifit, Multifit_nlin,
Multimin, Multiroots, Odeiv, Permutation
Poly, Qrng, Rng, Roots, Siman (Simulated Annealing)
Special Functions, Spline

GSL >= 1.3 and numerical python are required.

It requires either Numeric or numarray.

Please send all bug reports, requests, patches to
[EMAIL PROTECTED]


Yours sincerely
      Pierre Schnizer



-- 
Please remove the nospam for direct reply
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to send an int over a socket

2005-02-04 Thread Pierre Quentel
Use string formatting :
msglen = '%16s' %len(testmessage)
will return a 16-byte string, beginning with spaces. Send it over your 
connection and use int() to get the message length

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


Re: How to read POSTed data

2005-02-06 Thread Pierre Quentel
Here is an example of how to get the POST data :
#def do_POST(self):
#ctype, pdict = 
cgi.parse_header(self.headers.getheader('content-type'))
#length = int(self.headers.getheader('content-length'))
#if ctype == 'multipart/form-data':
#self.body = cgi.parse_multipart(self.rfile, pdict)
#elif ctype == 'application/x-www-form-urlencoded':
#qs = self.rfile.read(length)
#self.body = cgi.parse_qs(qs, keep_blank_values=1)
#else:
#self.body = {}   # Unknown content-type
## throw away additional data [see bug #427345]
#while select.select([self.rfile._sock], [], [], 0)[0]:
#if not self.rfile._sock.recv(1):
#break
#self.handle_data()

where handle_data() is the method where you will process the data received
The part related to bug #427345 is copied from CGIHTTPServer
For an example of use you can take a look at the CustomHTTPServer in 
Karrigell (http://karrigell.sourceforge.net)

A+,
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Strange os.path.exists() behaviour

2005-07-06 Thread Pierre Quentel
os.path.exists(path) returns True if "path" exists

But on Windows it also returns True for "path" followed by any number of 
dots :

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> import os
 >>> os.path.exists('Lib/os.py')
True# expected
 >>> os.path.exists('Lib/os.py.')
True# unexpected
 >>> os.path.exists('Lib/os.py.')
True    # unexpected
 >>>

Is there a reason for this ? Is there a test that returns True only for 
the really existing path ?

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


Concurrent access behind an asynchronous server

2005-09-18 Thread Pierre Quentel
Sorry if the question seems naive, but is there a risk of concurrent 
accesses to a database if it is accessed only by scripts called by 
requests to an asynchronous server ?

I have the same question for a server built on the non-threaded version 
of SocketServer.TCPServer

A+
Pierre
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to read POSTed data

2005-02-06 Thread Pierre Quentel

Pierre, I am repeating some questions I already stated in another thread, 
'CGI POST problem', but do you have any opinions on how CGIHTTPServer's 
do_POST handles requests?  It looks to me like it always expects form data 
to be part of the POST command header, in the path of the URL, just like a 
GET request.  Am I understanding the code incorrectly?  
The code in CGIHTTPServer is not very easy to understand, but it does
read the request body, as many bytes as indicated in the Content-Length
header. See line 262 (in the Python 2.4 distribution) or 250 in Python 
2.3 (this is the Windows version) :

data = self.rfile.read(nbytes)
Then this data is sent to the standard input of the CGI script. If this 
script is a Python program using the cgi module, it usually creates a 
cgi.FieldStorage() instance : upon creation, the standard input is read 
(in self.read_urlencoded() for instance) and the string collected is 
processed to produce a dictionary-like object, with keys matching the 
form field names

This is compliant with the CGI specification (HTTP doesn't say anything 
about the management of data sent by POST requests). The code I sent is 
an alternative to CGI, leaving the management of this data (available in 
self.body) to a method of the RequestHandler instance

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


negative integer division

2005-02-07 Thread Imbaud Pierre
integer division and modulo gives different results in c and python, 
when negative numbers
are involved. take gdb as a widely available c interpreter
 print -2 /3
0 for c, -1 for python.
more amazing, modulos of negative number give negative values! (in c).
from an algebraic point of view, python seems right, but I thought 
python conformity to the underlying c compiler was a strong commitment, 
obviously not here, and I found no explanation whatsoever in python doc.
no actual programming challenge for me here, I just had this bug, after 
confidently translating from python to c.

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


Re: convert list of tuples into several lists

2005-02-10 Thread Pierre Quentel
Steven Bethard a écrit :
Cappy2112 wrote:
What does the leading * do?

Tells Python to use the following iterable as the (remainder of the) 
argument list:

Could someone explain why this doesn't work :
Python 2.3.2 (#49, Oct  2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(*args,**kw):
... print args, kw
...
>>> f(*[1,2])
(1, 2) {}
>>> f(*[1,2],x=1)
  File "", line 1
f(*[1,2],x=1)
 ^
SyntaxError: invalid syntax
>>>

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


Re: For American numbers

2005-02-12 Thread Pierre Hanser
Peter Hansen wrote:
Scott David Daniels wrote:
Kind of fun exercise (no good for British English).
def units(value, units='bytes'):
magnitude = abs(value)
if magnitude >= 1000:
for prefix in ['kilo mega giga tera peta '
   'exa zetta yotta').split():
magnitude /= 1000.
if magnitude < 1000.:
break

Only for hard drive manufacturers, perhaps.
For the rest of the computer world, unless I've missed
a changing of the guard or something, "kilo" is 1024
and "mega" is 1024*1024 and so forth...
-Peter
even for cpu frequency?
--
http://mail.python.org/mailman/listinfo/python-list


Re: low-end persistence strategies?

2005-02-17 Thread Pierre Quentel
Maybe you'll find this too naive, but why do you want to avoid 
concurrent accesses to a database that will be accessed 12 times a day ?

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


Re: low-end persistence strategies?

2005-02-17 Thread Pierre Quentel
If a dozen people click the url in the next day, several of
them will probably in the first minute or so after the email goes out.
So two simultaneous clicks isn't implausible.

More generally, I don't like writing code with bugs even if the bugs
have fairly low chance of causing trouble.  So I'm looking for the
easiest way to do this kind of thing without bugs.
Even if the 12 requests occur in the same 5 minutes, the time needed for 
a read or write operation on a small base of any kind (flat file, dbm, 
shelve, etc) is so small that the probability of concurrence is very 
close to zero

If you still want to avoid it, you'll have to pay some price. The most 
simple and portable is a client/server mode, as suggested for KirbyBase 
for instance. Yes, you have to run the server 24 hours a day, but you're 
already running the web server 24/7 anyway
--
http://mail.python.org/mailman/listinfo/python-list


Re: Probably over my head... Trying to get Font Names

2005-02-18 Thread Pierre Quentel
"Samantha" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> I am attempting to extract the Font Names from the installed windows fonts. 
> I am having a heck of a time getting these rather than the file names. 
> Examples can be seen by going to Control Panel > Fonts
> 
> Any help or direction is appreciated.
> S

Try this :

Python 2.3.2 (#49, Oct  2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from Tkinter import Tk
>>> import tkFont
>>> root=Tk()
>>> print tkFont.families(root)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recommended way of generating HTML from Python

2005-02-20 Thread Pierre Quentel
Here are a couple of pointers. I agree with Michele that it would be 
nice to have some kind of standardization. Maybe this would be worth a 
post to the Web-SIG ?

- I posted a 70-line recipe on the Python Cookbook, a sort of poor man's 
HTMLGen called HTMLTags
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366000
with a syntax like this :

# print HTML( HEAD(TITLE('Test document')) +
#BODY(H1('This is a test document')+
#TEXT('First line')+BR()+
#TEXT('Second line')))
The use of addition allows for shortcuts like
print Sum([ TR(TD(i)+TD(i*i)) for i in range(100) ])
where Sum works like the built-in sum, but sum only works for numbers 
apparently

- in the Cookbook someone mentioned the HyperText package, published in 
2000 by Andy Dustman : http://dustman.net/andy/python/HyperText/

It uses this syntax :
# print TABLE(
#TR((TH('SPAM'), TH('EGGS')),
#TR(TD('foo','bar', colspan=2))
# )
The package also handles XML, SGML etc.
- I wrote to Andy and he said there was also Living Logic's XIST :
http://www.livinglogic.de/Python/xist/index.html
An example taken from the site :
#node = xsc.Frag(
#  xml.XML10(),
#  html.DocTypeXHTML10transitional(),
#  html.html(
#  html.head(
# meta.contenttype(),
# html.title("Example page")
#  ),
#  html.body(
# html.h1("Welcome to the example page"),
# html.p(
#"This example page has a link to the ",
#html.a("Python home page", href="http://www.python.org/";),
#"."
# )
#  )
#   )
# )
#
# print node.conv().asBytes(encoding="us-ascii")
--
http://mail.python.org/mailman/listinfo/python-list


Re: intersection of 2 list of pairs

2005-02-21 Thread Pierre Quentel
Another method is to build two sets of sets, one for E1 and one for E2, 
then make the intersection of these sets

- with Python 2.3
>>> E1=[('a','g'),('r','s')]
>>> E2=[('g','a'),('r','q'),('f','h')]
>>> from sets import Set,ImmutableSet
>>> f=Set([ImmutableSet(s) for s in E1])& Set([ImmutableSet(s) for s in 
E2])
>>> [tuple(x) for x in f]
[('a', 'g')]

- with Python 2.4
>>> E1=[('a','g'),('r','s')]
>>> E2=[('g','a'),('r','q'),('f','h')]
>>> f=set([frozenset(s) for s in E1]) & set([frozenset(s) for s in E2])
>>> [tuple(x) for x in f]
[('a', 'g')]
You must use ImmutableSet or frozenset to be able to create a set of sets
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter and Text() widget interactivity ?

2005-03-01 Thread Pierre Quentel
Tonino a écrit :
Hi,
I have a small Tkinter app that gets data from a socket connection to a
"server".  The app has a Text() widget to display the info that it gets
from the socket connection.  I have the ability to stop the text at any
point.
What I want to be able todo is select a line from the Text() window and
double click or whatever on it to open a new window with that selected
text as a paramater to the new window.
The app is a network sniffer and I want to be able to select a line
from the Text() window and run a decode on the data from the sniffer.
any help and pointers would help.  I have no idea of what to search for
;)
Thanks
Here is an example of what you can do :
# from Tkinter import *
#
# def action(event):
# begin,end=event.widget.tag_ranges(SEL)
# selected_text=event.widget.get(begin,end)
# new_window = Toplevel(root)
# n_text = Text(new_window)
# n_text.pack()
# n_text.insert(END,selected_text)
#
# root=Tk()
# t=Text(root)
# t.pack()
# t.tag_bind(SEL,"",action)
# t.insert(END,"Sweetness, sweetness I was only joking when I said\n")
# t.insert(END,"By rights you should be bludgeoned in your bed")
#
# root.mainloop()
In a Text widget you can add event bindings to tags, the selected text 
has the built-in tag SEL. I don't think you can bind the event 
 to it because double-clicking on a text widget selects 
the word the cursor is on ; here I use  (left click) but you 
can use other events

In the function "action" the widget where the event occured is 
event.widget (the Text widget). Its method tag_ranges returns the 
beginning and end of the text with the specified tag (here SEL), then 
you get the selected text by the method get() of the text widget

This is explained in "An introduction to Tkinter" by Fredrik Lundh, in 
the chapter "The Text Widget" 
http://www.pythonware.com/library/tkinter/introduction/

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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-03-01 Thread Pierre Schnizer

In case you are still interested pygsl wraps the GSL solver.

from pygsl import poly
pc = poly.poly_complex(3)
tmp, rs = pc.solve((2,3,1))
print rs


You get pygsl at http://sourceforge.net/projects/pygsl/
Pierre
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Widget geometry ?

2005-03-11 Thread Pierre Quentel
PGMoscatt a écrit :
Hi All,
I am trying to create a dialog which will have a number of components but
having trouble with the placement of various widgets.
For example, in my code below you will see I am trying to insert alabel but
I want the label to be in the top-left of the dialog but it dosen't want to
go there.
What am I doing wrong ?
Pete

from Tkinter import *
class show_settings_dialog:
 def __init__(self,parent):
  top = self.top = Toplevel(parent)
  top.title("General Settings...")
  top["height"]=300
  top["width"]=300
  top.pack_propagate(0)
  l1 = Label(top,text="User Name:").grid(row=0, sticky=W)

  b = Button(top,text="Ok",command=self.ok)
  b.pack(pady=40)
  
  
  
 def ok(self):
  self.top.destroy()

You are mixing pack() and grid() to place widgets in the same container. 
Try doing b.grid(row=0,column=1) instead

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


Re: problem with tkinter

2005-03-29 Thread Pierre Quentel
Instead of indexing self.lab by strings, you can index them by the 
attributes themselves : self.lab[self.i], and change line 23 into

 for var in (self.s, self,i)
For your example, I wouldn't have used the "text" option in the 
definition of the labels, then "textvariable" in the callback method 
(procedi) ; I would have used only "text" and no IntVar or StringVar, 
just an integer and a string :

class MiaApp:
def __init__(self, genitore):
   self.mioGenitore = genitore
   self.i = 42
   self.s = "Baobab"
   self.lab = {}
   self.lab[self.i] = Label(self.mioGenitore)
   self.lab[self.i].configure(width = 30, relief = RIDGE,
 text = "[vuota]")
   self.lab[self.i].pack()
   self.lab[self.s] = Label(self.mioGenitore)
   self.lab[self.s].configure(width = 30, relief = RIDGE,
 text = "[vuota]")
   self.lab[self.s].pack()
   self.but = Button(self.mioGenitore)
   self.but.configure(text = "Vai!", command = self.procedi)
   self.but.pack()
def procedi(self):
   for var in (self.i, self.s):
 self.lab[var].configure(text = var)
Regards,
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Re: Web application toolkit recommendation?

2005-04-06 Thread quentel . pierre
You can also take a look at Karrigell
(http://karrigell.sourceforge.net). You can write pure Python scripts
or use a PHP-like syntax, and it is shipped with gadfly, an SQL engine,
and with KirbyBase, a database engine which uses a Pythonic syntax. As
for all the web frameworks, you can also work with the APIs available
for almost any database under the sun

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


Re: Web application toolkit recommendation?

2005-04-07 Thread Pierre Quentel
[EMAIL PROTECTED] a écrit :
I have looked briefly at Karrigell. does it support user logins?
S
Yes, you can take a look at the "portal" demo to see how it works
Regards,
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Re: Declaring variables from a list

2005-04-09 Thread Pierre Quentel
You can use the built-in statement exec 
(http://www.python.org/doc/2.4.1/ref/exec.html) :

# Blob = ['Var1', 'Var2', 'vAR3']
# i = 5
# for listitems in Blob:
# i += 1
# exec('%s = i' %listitems)
#
# print Var1, Var2, vAR3
Regards,
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Problem deriving a class from the built-in file object

2005-04-22 Thread Pierre Rouleau
Hi all!
I'm trying to extend the functionality of the file object by creating a 
class that derives from file.  MyFile class re-implements __init__(), 
write(), writelines() and close() to augment the capabilities of file.

All works fine, except for one thing:  'print >> myfile'  does not 
execute Myfile.write(), it executes the file.write().   If I execute 
myfile.write() explicitly, then Myfile.write() is called as expected.

I was not expecting that behaviour.  I though that 'print >> afileobject 
' would execute the afileobject.write() as you can easily obtain by 
defining a simple file-like class that implements write() and writeline().

I am running Python 2.3.4.  Can't move to 2.4 yet.
Is it the expected behavior?

# M y F i l e -- Testing inheritance from file --
# ^^^
#
class MyFile(file):
""" Testing new-style class inheritance from file"""
#
def __init__(self, name, mode="r", buffering=-1, verbose=False):
"""Constructor"""
self.was_modified = False
self.verbose = verbose
super(MyFile, self).__init__(name, mode, buffering)
if self.verbose:
print "MyFile %s is opened.  The mode is: %s" % (self.name, 
self.mode)

#
def write(self, a_string):
""" Write a string to the file."""
super(MyFile, self).write(a_string)
self.was_modified = True
#
def writelines(self, sequence):
""" Write a sequence of strings to the file. """
super(MyFile, self).writelines(sequence)
self.was_modified = True
#
def close(self) :
"""Close the file."""
if self.verbose:
print "Closing file %s" % self.name
super(MyFile, self).close()
self.was_modified = False

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


Why is Python not supporting full derivation of built-in file class?

2005-04-23 Thread Pierre Rouleau
Greetings,
I'm wondering why the >> operator does not use the write() method of a 
class derived from the built-in file class as in DerivedFile below.

In the following example:
- StringFile is just a file-like string accumulation class that can be 
used in place of a real file to accumulate strings that would otherwise 
be printed.  Works fine, can accumulate strings with the >> operator, 
but is not a true file.

- DelegatedFile is a new-style class, a true file class, which provides 
all the features of a real file through delegation.  It also works fine 
and can accumulate string with the >> operator.

- DerivedFile is a new-style class that is derived from file.  It 
behaves like a true file, but the >> operator does not call its write() 
method.  Why is that?

Is this related to the fact that on object from that class is seen as a 
file (as shown at the end of the code session below)?

Is this intended or is it a flaw in the language that is waiting to be 
fixed?

>>> import sys
>>> sys.ps2=' ... '; sys.ps1=' >>> '
 >>> def hello(stream=None):
 ... if stream is None:
 ... stream = sys.stdout
 ... print >> stream, "Bonjour!"
 ...
 >>> # Using a duck-typing to define a class
 ... # that behaves like a file for writing only.
 ... class StringFile:
 ... "A file-like object to accumulate strings"
 ... # print >> aStringFile works
 ... def __init__(self):
 ... self.strings = []
 ... def write(self, text):
 ... self.strings.append(text)
 ... def writelines(self, lines):
 ... self.strings.extend(lines)
 ...
 >>> # Using delegation to file to create a class that
 ... # extends the built-in file object.
 ... class DelegatedFile(object):
 ... "A file-like object to accumulate strings"
 ... # print >> aStringFile works
 ... def __init__(self, *args):
 ... self.strings = []
 ... self._file = file(*args)
 ... def __getattr__(self, name) :
 ... return getattr(self._file, name)
 ... def write(self, text):
 ... self.strings.append(text)
 ... self._file.write(text)
 ... def writelines(self, lines):
 ... self.strings.extend(lines)
 ... self._file.writelines(lines)
 ...
 >>> # Using derivation from file to create a class
 ... # that extends file. But has a flaw in the use of the >> operator!
 ... class DerivedFile(file):
 ... "A file object that accumulated written strings"
 ... # print >> a DerivedFile doe NOT work!
 ... def __init__(self, *args):
 ... self.strings = []
 ... file.__init__(self, *args)
 ... def write(self, text):
 ... self.strings.append(text)
 ... file.write(self, text)
 ... # super(DerivedFile, self).write(text)
 ... def writelines(self, lines):
 ... self.strings.extend(lines)
 ... file.writelines(self, lines)
 ... # super(DerivedFile, self).writelines(lines)
 ...
 >>> hello()
Bonjour!
 >>>
 >>> sf = StringFile()
 >>> hello(sf)
 >>> sf.strings
['Bonjour!', '\n']
 >>>
 >>> dg = DelegatedFile("temp.txt","w")
 >>> hello(dg)
 >>> dg.close()
 >>> dg.strings
['Bonjour!', '\n']
 >>> for line in file("temp.txt"): print line
 ...
Bonjour!
 >>> df = DerivedFile("temp2.txt","w")
 >>> hello(df)
 >>> df.close()
 >>> df.strings
[]
 >>> for line in file("temp2.txt"): print line
 ...
Bonjour!
 >>>
 >>> sf
<__main__.StringFile instance at 0x008D86C0>
 >>> dg
<__main__.DelegatedFile object at 0x008D50B0>
 >>> df

 >>>
--
Pierre Rouleau
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is Python not supporting full derivation of built-in file class?

2005-04-25 Thread Pierre Rouleau
Jeff Epler wrote:
This issue was discussed in another recent python-list thread, called
"Writing to stdout and a log file".
My second post includes a patch to Python's "fileobject.c" that made the
code that started that thread work, but for reasons I mentioned in that
post I didn't want to push for inclusion of my patch.  I didn't check,
but it will probably allow your code to work too.
If you feel differently, then the thing to do is probably to submit the
patch plus a test case to the sf.net patch tracker for python
(sf.net/projects/python, click on "patches".  you'll need a sourceforge
account to submit the patch)
Jeff
PS I did allow the Python test suite to run to completion after I wrote
that message.  It didn't produce any failures or unexpected skips on my
platform.
Thanks.  I never got involved in Python development before, so I will 
take a look at the development process.  I took a quick look at the 
affected C files and must confess that I need more time looking at them 
to learn everything around it. However, I think that the behaviour of 
file handling should change so that any class derived from file should 
support the >> operator 'properly' (ie the derived class write() method 
should be called).

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


Brython (Python in the browser)

2013-12-26 Thread Pierre Quentel
Hi,

Ever wanted to use Python instead of Javascript for web client programming ? 
Take a look at Brython, an implementation of Python 3 in the browser, with an 
interface with DOM elements and events

Its use is very simple :
- load the Javascript library brython.js : 

Re: Brython (Python in the browser)

2013-12-27 Thread Pierre Quentel
Le vendredi 27 décembre 2013 15:56:33 UTC+1, jonas.t...@gmail.com a écrit :
> Den fredagen den 27:e december 2013 kl. 07:14:35 UTC+1 skrev Pierre Quentel:
> 
> > Hi,
> 
> > 
> 
> > 
> 
> > 
> 
> > Ever wanted to use Python instead of Javascript for web client programming 
> > ? Take a look at Brython, an implementation of Python 3 in the browser, 
> > with an interface with DOM elements and events
> 
> > 
> 
> > 
> 
> > 
> 
> > Its use is very simple :
> 
> > 
> 
> > - load the Javascript library brython.js : 

Re: Brython (Python in the browser)

2013-12-27 Thread Pierre Quentel
Le vendredi 27 décembre 2013 17:12:09 UTC+1, Johannes Schneider a écrit :
> On 27.12.2013 07:14, Pierre Quentel wrote:
> 
> > Hi,
> 
> >
> 
> > Ever wanted to use Python instead of Javascript for web client programming 
> > ? Take a look at Brython, an implementation of Python 3 in the browser, 
> > with an interface with DOM elements and events
> 
> >
> 
> > Its use is very simple :
> 
> > - load the Javascript library brython.js : 

[ANN] Brython 3.0.0 relased

2014-11-16 Thread Pierre Quentel
Hi,

Version 3.0.0 of Brython has been released recently

Brython is an implementation of Python 3 running in the browser, with an 
interface to DOM elements and events. It allows writing web client applications 
with Python instead of Javascript.

Python programs are inserted in the HTML page inside tags 

Problem with the console on the new python.org site

2014-02-23 Thread Pierre Quentel
The new home page of python.org is very nice, congratulations !

But there is a problem with the online console provided by PythonAnywhere : 
with my azerty keyboard, I can't enter characters such as ) or ] - very 
annoying !

It this going to be fixed soon ?

- Pierre
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Problem with the console on the new python.org site

2014-02-24 Thread Pierre Quentel
Le lundi 24 février 2014 14:19:12 UTC+1, Jean-Michel Pichavant a écrit :
> - Original Message -
> > On Sun, 23 Feb 2014 10:20:15 -0800, Pierre Quentel wrote:
> > 
> > > The new home page of python.org is very nice, congratulations !
> > 
> > The best I can say about it is that I'm extremely underwhelmed by the
> > design, which is far more "busy" and colourful than the old design
> > (this
> > is not a complement), and not happy that it doesn't work correctly
> > without Javascript.
> 
> Steven, you must have been the grumpy smurf in another life ;)
>  
> > > But there is a problem with the online console provided by
> > > PythonAnywhere : with my azerty keyboard, I can't enter characters
> > > such
> > > as ) or ] - very annoying !
> 
> I have an azerty keyboard and it works just fine, your problem must be 
> something else.

It seems to depend on the browser. I had the problem with Firefox 27.0.1 on 
Windows XP ; the link "Feedback" didn't work with this browser, this is why I 
posted here

With Chrome 33.0.1750.117 m and Opera 12.12 the characters are recognised

I reported the issue on the feedback form, and discovered it was already known 
by the PythonAnywhere team (https://www.pythonanywhere.com/forums/topic/213/). 
Hope it will be fixed quickly, it doesn't give a good impression for newcomers 
to Python whose first contact with the language is this console
> 
> JM
> 
> 
> -- IMPORTANT NOTICE: 
> 
> The contents of this email and any attachments are confidential and may also 
> be privileged. If you are not the intended recipient, please notify the 
> sender immediately and do not disclose the contents to any other person, use 
> it for any purpose, or store or copy the information in any medium. Thank you.

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


Iterators membership testing

2015-08-09 Thread Pierre Quentel
The documentation at 
https://docs.python.org/3.5/reference/expressions.html#not-in says :

"For user-defined classes which do not define __contains__() but do define 
__iter__(), x in y is true if some value z with x == z is produced while 
iterating over y. If an exception is raised during the iteration, it is as if 
in raised that exception."

However, if I define a class with

class A:

def __init__(self, x):
self.x = x
self.counter = -1

def __iter__(self):
return self

def __next__(self):
self.counter += 1
if self.counter >= self.x:
raise StopIteration
return self.counter

and test for membership with

iterator = A(10)

for i in iterator:
assert i in iterator, '%s not found' %i

I get an assertion error. Setting a trace on __next__ suggests that for 
membership testing, the interpreter consumes the iterator until the searched 
value is found (or until exhaustion), then it resumes iteration at this point.
For instance :

>>> iterator = A(10)
>>> for i in iterator:
...  print(i)
...  assert i+1 in iterator
...
0
2
4
6
8
>>>

If this is correct, should the documentation mention it ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iterators membership testing

2015-08-09 Thread Pierre Quentel
Le dimanche 9 août 2015 11:25:17 UTC+2, Chris Angelico a écrit :
> On Sun, Aug 9, 2015 at 7:06 PM, Pierre Quentel  
> wrote:
> > "For user-defined classes which do not define __contains__() but do define
> > __iter__(), x in y is true if some value z with x == z is produced while
> > iterating over y. If an exception is raised during the iteration, it is as 
> > if
> > in raised that exception."
> >
> > ...
> > I get an assertion error. Setting a trace on __next__ suggests that for
> > membership testing, the interpreter consumes the iterator until the searched
> > value is found (or until exhaustion), then it resumes iteration at this 
> > point.
> 
> That's exactly right. The only way for the interpreter to handle 'in'
> on an iterator is something like this:
> 
> def contains(iter, obj):
> for val in iter:
> if val == obj: return True
> return False
> 
> That's what the docs describe. So what you have is something like this:
> 
> for i in iterator:
> for j in iterator:
> if i == j: break
> else:
> assert False, '%s not found' %i
> 
> You're dragging values from the same iterator, so you're consuming it
> as part of your membership test. You can do this kind of thing:
> 
> >>> 5 in A(10)
> True
> 
> but if you've already consumed a few values, those won't be in the
> iterator any more:
> 
> >>> x = A(10)
> >>> next(x)
> 0
> >>> next(x)
> 1
> >>> next(x)
> 2
> >>> next(x)
> 3
> >>> 2 in x
> False
> 
> This is simply how iterators work. They're very different from
> repeatable iterables like lists or range objects, where you _can_ test
> for membership that way:
> 
> >>> x = [10,20,30]
> >>> for i in x: assert i in x
> ...
> >>> x = iter([10,20,30])
> >>> for i in x: assert i in x
> ...
> Traceback (most recent call last):
>   File "", line 1, in 
> AssertionError
> 
> Note that I _could_ create a list that would pass this assertion,
> simply by duplicating every value:
> 
> >>> x = iter([10,10,20,20,30,30])
> >>> for i in x: assert i in x
> ...
> 
> But it's iterating only three times here, and the 'in' check is
> consuming the other three values. Once your A(10) has yielded some
> value, it will never yield it again, so the assertion can never pass.
> 
> Does that explain matters?
> 
> ChrisA

Thanks for the explanation. I understand that an iterator can't test membership 
any other way, but I'm still worried about how the documentation explains it. 
Reading it, I naively expected that an iterator which produces the integer 0 
such as the one included in my post would say that "0 in iterator" is True, 
because "some value z with 0 == z is produced while iterating over y".

Shouldn't it be more clear if the documentation said something like : "For 
user-defined classes which do not define __contains__() but do define 
__iter__(), x in y consumes the iterator y until some value z with x == z is 
produced" ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iterators membership testing

2015-08-09 Thread Pierre Quentel
> The trap you're seeing here is that iterating over an iterator always
> consumes it, but mentally, you're expecting this to be iterating over
> a new instance of the same sequence. 

No, I just tried to apply what I read in the docs :

1. I have y = A(10) which is an instance of a class which does not define 
__contains__ but does define __iter__

2. The value z = 0 is produced while iterating over y.

3. The sentence "x in y is true if some value z with x == z is produced while 
iterating over y" lead me to think that "0 in y" would be true.
-- 
https://mail.python.org/mailman/listinfo/python-list


Partially invalid sys.path - how can I fix it (not append to it)?

2015-09-28 Thread Pierre Rouleau
Hi,

On a OS/X 101.10.5 (Yosemite) system, the system Python just got updated to 
2.7.10 but it sys.path is partially invalid. How can I fix that?  I don't want 
to add something in PYTHONPATH.  I know I can create a softlink at the invalid 
location to where the real files are located.I just want to understand why 
that sys.path[6] (see below) is invalid and fix it to point to the valid 
directory.  Details follow:


I am running Python 2.7.10:

[~]$ python
Python 2.7.10 (default, Jul 14 2015, 19:46:27) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

First, see when I get the sys.path before site.py is imported::

[~]$ python -S -c "import sys, pprint; print sys.prefix; 
pprint.pprint(sys.path)"
/usr
['',
 '/usr/lib/python27.zip',
 '/usr/lib/python2.7/',
 '/usr/lib/python2.7/plat-darwin',
 '/usr/lib/python2.7/plat-mac',
 '/usr/lib/python2.7/plat-mac/lib-scriptpackages',
 '/usr/lib/python2.7/../../Extras/lib/python',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload']


[~]$ python -c "import sys, pprint; print sys.prefix; pprint.pprint(sys.path)"
/usr
['',
 '/usr/lib/python27.zip',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-darwin',
 '/usr/lib/python2.7/plat-mac',
 '/usr/lib/python2.7/plat-mac/lib-scriptpackages',
 '/usr/Extras/lib/python',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/Library/Python/2.7/site-packages']
[~]$ 

Notice sys.path[6].  It is '/usr/lib/python2.7/../../Extras/lib/python', which 
when going through site gets normalized to '/usr/Extras/lib/python'.  That 
directory is invalid on my system.  It should either be:

- The real location: 
/System/Library/Frameworks/Python.frameworks/Versions/2.7/Extras/lib/python

or

- the corresponding softlink to that:
/usr/lib/python2.7/Extras/lib/python


Also note that the sys.prefix is "/usr"
I think it should be "/usr/lib/python2.7" or 
"/System/Library/Frameworks/Python.framework/Versions/2.7"


Other Python installed on that system include Python 3.5 (installed via the 
Python 3.5 DMG installer) and Python 2.7.9 installed with homebrew.  For these 
versions of Python I see something that matches the content of the system 
storage:

- Python 3.5: sys.prefix = '/Library/Frameworks/Python.framework/Versions/3.5'
- Python 2.7.9: sys.prefix = 
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7'

Does anyone know how to fix the path generated in sys.path without adding the 
real directory path in PYTHONPATH?


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


[ANN] Karrigell-4.3.6 released

2011-10-31 Thread Pierre Quentel
Hi,

A new version of the Karrigell web framework for Python 3.2+ has just
been released on http://code.google.com/p/karrigell/

One of the oldest Python web frameworks around (the first version was
released back in 2002), it now has 2 main versions, one for Python 2
and another one for Python 3. The Python 2.x version is available at
http://karrigell.sf.net ; this branch is maintained, but no new
feature is going to be developed

All the development work is now focused on the version for Python 3.
The first release was published in February and we are already at the
10th release

Karrigell's design is about simplicity for the programmer and
integration of all the web environment in the scripts namespace. For
instance, the "Hello world" script requires 2 lines :

def index():
return "Hello world"

All the HTML tags are available as classes in the scripts namespace :

def index():
return HTML(BODY("Hello world"))

To build an HTML document as a tree, the HTML tags objects support the
operators + (add brother) and <= (add child) :

def index():
form = FORM(action="insert",method="post")
form <= INPUT(name="foo")+BR()+INPUT(name="bar")
form <= INPUT(Type="submit",value="Ok")
return HTML(BODY(form))

The scripts can be served by a built-in web server, or through the
Apache server, either on CGI mode or using the WSGI interface

The package obvioulsy has built-in support for usual features such as
cookie and session management, localization, user login/logout/role
management. It also includes a complete documentation, with a tutorial
and a set of how-to's

A helpful and friendly community welcomes users at 
http://groups.google.com/group/karrigell

Enjoy !
Pierre
-- 
http://mail.python.org/mailman/listinfo/python-list


PSF News: Guido van Rossum quitting Python to develop new, more difficult to learn, language.

2013-04-01 Thread Pierre O'Dee
PSF [Beaverton, OR] 1 April 2013 -- At a news conference held
earlier today, Guido van Rossum announced that he is quitting
Python to develop a new language.

"Python just makes programming too damn easy and too bug-free,"
Guido said as part of his remarks in a brief, prepared statement.
He added, "The way things are going, soon, everyone in the world
will be programming in Python -- even children!"

Guido went on to say that he's now working on a new language
called Giddy-up-and-Go which will take the worst features of C++,
Java, and French combined with elements of both PHP and Klingon
syntax. He said that this new endeavor should put the work and
frustration back into programming "[where] it ought to be."
Responding to a reporter's question in a brief Q&A following the
announcement, Guido said, "Real programmers don't need no
stinkin' easy and intuitive language to program with."

Some features have already been hinted at for the new language.
No Unicode -- BAUDOT is expected to be the new character
encoding. Numeric types have been eliminated as it's no longer
relevant or possible for most students and younger PhDs to do
even simple arithmetic considering the current state of the
so-called educational system. One surprising feature is that
everything will be a subject using Guido's new subject-oriented
programming (SOP) paradigm. Other sources said that variables
(subjects in the new paradigm) will now be passed by gas.

Python 3.3 will be the last version of Python. Look for
announcements soon for the new Giddy-up-and-Go mailing lists.

PSF will be selling its holdings to Oracle as they've embraced
the open-source philosophy so freely and warmly. One insider
shared unconfirmed rumors that Mr. Johnson will be attempting to
revive and steer the now defunct Python language -- which
elicited further concerns amongst the somewhat bewildered Python
community.

All newsgroups mentioning Python -- the full Monty -- will be
closed today.

--Pierre O'Dee, self-appointed spokesman for the PSF
-- 
http://mail.python.org/mailman/listinfo/python-list


"0 in [True,False]" returns True

2005-12-12 Thread Pierre Quentel
Hi all,

In some program I was testing if a variable was a boolean, with this 
test : if v in [True,False]

My script didn't work in some cases and I eventually found that for v = 
0 the test returned True

So I changed my test for the obvious "if type(v) is bool", but I still 
find it confusing that "0 in [True,False]" returns True

By the way, I searched in the documentation what "obj in list" meant and 
couldn't find a precise definition (does it test for equality or 
identity with one of the values in list ? equality, it seems) ; did I 
miss something ?

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


Re: "0 in [True,False]" returns True

2005-12-13 Thread quentel . pierre
Ok, I'll explain why I wanted to test if the value was a boolean

I have a program that generates HTML tags with attributes. The
principle is that
TAG('text',arg1=val1,arg2=val2)
generates
text

For HTML attributes that don't have an explicit value (such as the
SELECTED attribute in OPTION) the keyword argument to the function must
have the value True

My program has a class for each tag, all derived from a generic TAG
class whose __init__ method takes the arguments :
def __init__(self, innerHTML="", **attrs):

I have to handle differently the cases where the value is a boolean or
another type:
- if it's a boolean then if the value is True, generate the argument
name ; if the value is False, don't generate anything
- if it's not a boolean, generate arg="val". Specifically, it val is 0,
generate val = "0"

Testing with "if v:" as suggested would fail for val = 0

Anyway, I exposed my silly "if v in [True,False]" just to give my
opinion that I found confusing that
0 in [True,False]
or (boolean type checking set aside)
0 in [1,range(2),False,'text']

return True

Regards,
Pierre

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


Re: "0 in [True,False]" returns True

2005-12-13 Thread quentel . pierre
Thanks for the link Carsten, the explanation is clear

I didn't know where to search in the Python documentation, there isn't
a section about keywords (always wondered why without daring to say -
now it's done). So I typed ' "in" operator Python ' in Google, which
gave :
- on the first page a link to AM Kuchling's and Moshe Zadka's "What's
new in Python 2.0" which said :
"obj in seq returns true if obj is present in the sequence seq; Python
computes this by simply trying every index of the sequence until either
obj is found or an IndexError is encountered"
- on the second page a link to the Python tutorial that says : "The
comparison operators in and not in check whether a value occurs (does
not occur) in a sequence"

I couldn't tell if "present in the sequence" or "obj is found" or
"occurs/does not occur in a sequence" meant "is equal to" or "is the
same object as". The answer you pointed me to is clear, but for some
reason I didn't have the idea of looking in the section "Sequence Types
-- str, unicode, list, tuple, buffer, xrange" for the definition of
"in" (after all "in" is also used in list comprehensions, generator
expressions, exec, etc... and for iteration on iterators)

Regards,
Pierre

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


Re: Which Python web framework is most like Ruby on Rails?

2005-12-21 Thread Pierre Quentel
Hello all,

I am Karrigell's author. I have chosen the GPL licence almost at random
(I saw that the Python licence was GPL-compatible), so I don't mind
switching to another Open Source licence if the GPL is liable to cause
problems. Which one would you advice : BSD ? Python licence ? another ?

Regards,
Pierre

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


Re: Which Python web framework is most like Ruby on Rails?

2005-12-21 Thread Pierre Quentel
I definitely don't want to invent another licence, there are enough of
them already !
Pierre

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


  1   2   3   4   >