Re: revive a generator

2011-10-21 Thread Yingjie Lan
> Here's an example of an explicit request to revive the generator:

> 
  g = (x*x for x in range(3))
  for x in g: print x
> 0
> 1
> 4
  g = (x*x for x in range(3)) # revive the generator
  for x in g: print x #now this will work
> 0
> 1
> 4
> 
> ChrisA


What if the generator is passed in as an argument 
when you are writing a function? That is, the expression
is not available? 

Secondly, it would be nice to automatically revive it.
For example, when another for-statement or other
equivalent is applied to it.

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


Re: revive a generator

2011-10-21 Thread Paul Rudin
Yingjie Lan  writes:

> - Original Message -
>> From: Paul Rudin 

>> Generators are like that - you consume them until they run out of
>> values. You could have done [x*x for x in range(3)] and then iterated
>> over that list as many times as you wanted.
>> 
>> A generator doesn't have to remember all the values it generates so it
>> can be more memory efficient that a list. Also it can, for example,
>> generate an infinite sequence.
>> 
>> 
> Thanks a lot to all who answered my question. 
> I am still not sure why should we enforce that 
> a generator can not be reused after an explicit 
> request to revive it?

The language has no explicit notion of a request to "revive" a
generator. You could use the same syntax to make a new generator that
yeilds the same values as the one you started with if that's what you
want. 

As we've already discussed if you want to iterate several times over the
same values then it probably makes sense to compute them and store them
in e.g. a list (although there are always trade-offs between storage use
and the cost of computing things again).



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


Re: revive a generator

2011-10-21 Thread Yingjie Lan
- Original Message -

> From: Paul Rudin 
> The language has no explicit notion of a request to "revive" a
> generator. You could use the same syntax to make a new generator that
> yeilds the same values as the one you started with if that's what you
> want. 
> 
> As we've already discussed if you want to iterate several times over the
> same values then it probably makes sense to compute them and store them
> in e.g. a list (although there are always trade-offs between storage use
> and the cost of computing things again).
> 

Oops, my former reply has the code indentation messed up 
by the mail system. Here is a reformatted one:


What if the generator involves a variable from another scope,
and before re-generating, the variable changed its value.
Also, the generator could be passed in as an argument,
so that we don't know its exact expression.

>>> vo = 34
>>> g = (vo*x for x in range(3))
>>> def myfun(g):
            for i in g: print(i)
            vo  += 3
            revive(g) #best if revived automatically
            for i in g: print(i)
>>> myfun(g)


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


Re: revive a generator

2011-10-21 Thread Yingjie Lan
- Original Message -

> From: Paul Rudin 
> To: [email protected]
> Cc: 
> Sent: Friday, October 21, 2011 3:27 PM
> Subject: Re: revive a generator
> 
> 
> The language has no explicit notion of a request to "revive" a
> generator. You could use the same syntax to make a new generator that
> yeilds the same values as the one you started with if that's what you
> want. 
> 
> As we've already discussed if you want to iterate several times over the
> same values then it probably makes sense to compute them and store them
> in e.g. a list (although there are always trade-offs between storage use
> and the cost of computing things again).
> 
> 


What if the generator involves a variable from another scope,
and before re-generating, the variable changed its value.
Also, the generator could be passed in as an argument,
so that we don't know its exact expression.

>>> vo = 34
>>> g = (vo*x for x in range(3))
>>> def myfun(g):
for i in g: print(i)
vo  += 3
revive(g) #best if revived automatically
for i in g: print(i)
myfun(g)

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


Problem with inheritance

2011-10-21 Thread Sverre
I have to classes a  and b


class a(object):
def __init__(self,x):
self.x = x
self.build()

def build(self):
return

class b(a):
def __init__(self,x):
a.__init__(self,x)
self.y = 0  # ???

def build(self):
# do something
self.y += 2*self.x

 t = b(1)

The line marked with "???" will no be executed and I don't know the
reason. This example is working as intended, but not not the code I'm
working on. I'm using Eclipse. I don't know how to debug this
problem.

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


Re: revive a generator

2011-10-21 Thread Paul Rudin
Yingjie Lan  writes:

>
>
> What if the generator involves a variable from another scope,
> and before re-generating, the variable changed its value.
> Also, the generator could be passed in as an argument,
> so that we don't know its exact expression.
>
 vo = 34
 g = (vo*x for x in range(3))
 def myfun(g):
>             for i in g: print(i)
>             vo  += 3
>             revive(g) #best if revived automatically
>             for i in g: print(i)
 myfun(g)
>
>


I'm not really sure whether you intend g to yield the original values
after your "revive" or new values based on the new value of vo.  But
still you can make a class that supports the iterator protocol and does
whatever you want (but you can't use the generator expression syntax).

If you want something along these lines you should probably read up on
the .send() part of the generator protocol.

As an aside you shouldn't really write code that uses a global in that
way.. it'll end up biting you eventually.

Anyway... we can speculate endlessly about non-existent language
constructs, but I think we've probably done this one to death.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: revive a generator

2011-10-21 Thread Chris Angelico
On Fri, Oct 21, 2011 at 7:02 PM, Yingjie Lan  wrote:
> What if the generator involves a variable from another scope,
> and before re-generating, the variable changed its value.
> Also, the generator could be passed in as an argument,
> so that we don't know its exact expression.
>

There's actually no way to know that the generator's even
deterministic. Try this, for instance:

>>> g=(input("Enter value %d or blank to stop: "%n) for n in range(1,11))
>>> for s in g:
if not s: break
print("Processing input: "+s)

It may not be particularly useful, but it's certainly legal. And this
generator cannot viably be restarted. The only way is to cast it to
list first, but that doesn't work when you have to stop reading
expressions from the generator part way.

What you could perhaps do is wrap the generator in something that
saves its values:

>>> class restartable(object):
def __init__(self,gen):
self.gen=gen
self.yielded=[]
self.iter=iter(self.yielded)
def restart(self):
self.iter=iter(self.yielded)
def __iter__(self):
return self
def __next__(self): # Remove the underscores for Python 2
try:
return self.iter.__next__()
except StopIteration:
pass
ret=self.gen.__next__()
self.yielded.append(ret)
return ret

>>> h=restartable(g)
>>> for i in h:
if not i: break
print("Using: ",i)
>>> h.restart()
>>> for i in h:
if not i: break
print("Using: ",i)

Complicated, but what this does is returns a value from its saved list
if there is one, otherwise returns a value from the original
generator. It can be restarted as many times as necessary, and any
time you read "past the end" of where you've read so far, the original
generator will be called upon.

Actually, this model might be useful for a repeatable random-number
generator. But those are more efficiently restarted by means of
reseeding the PRNG.

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


Re: Problem with inheritance

2011-10-21 Thread Chris Angelico
On Fri, Oct 21, 2011 at 7:07 PM, Sverre  wrote:
> The line marked with "???" will no be executed and I don't know the
> reason. This example is working as intended, but not not the code I'm
> working on. I'm using Eclipse. I don't know how to debug this
> problem.
>

Did you notice the error you got when you tried? Copying and pasting
your example into IDLE shows this (Python 3):

>>> t=b(1)
Traceback (most recent call last):
  File "", line 1, in 
t=b(1)
  File "", line 3, in __init__
a.__init__(self,x)
  File "", line 4, in __init__
self.build()
  File "", line 8, in build
self.y += 2*self.x
AttributeError: 'b' object has no attribute 'y'

When a calls self.build(), it calls b's build() function. That tries
to modify self.y, which then fails. If you put the self.y = 0 line
above the chaining call to a.__init__, all is well.

Incidentally, you may wish to replace the a.__init__ call with this:
super().__init__(x)

That way, you're not repeating the name 'a', and if you change the
inheritance tree, you don't need to change your code.

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


Re: Problem with inheritance

2011-10-21 Thread Sverre
On Oct 21, 10:07 am, Sverre  wrote:
> I have to classes a  and b
>
> class a(object):
>     def __init__(self,x):
>         self.x = x
>         self.build()
>
>     def build(self):
>         return
>
> class b(a):
>     def __init__(self,x):
>         a.__init__(self,x)
>         self.y = 0  # ???
>
>     def build(self):
>         # do something
>         self.y += 2*self.x
>
>  t = b(1)
>
> The line marked with "???" will no be executed and I don't know the
> reason. This example is working as intended, but not not the code I'm
> working on. I'm using Eclipse. I don't know how to debug this
> problem.

I found the solution. I caused an exception in b.build that wasn't
reported by Eclipse properly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: revive a generator

2011-10-21 Thread Yingjie Lan
- Original Message -

> From: Paul Rudin 
> 
> I'm not really sure whether you intend g to yield the original values
> after your "revive" or new values based on the new value of vo.  But
> still you can make a class that supports the iterator protocol and does
> whatever you want (but you can't use the generator expression syntax).
> 
> If you want something along these lines you should probably read up on
> the .send() part of the generator protocol.
> 
> As an aside you shouldn't really write code that uses a global in that
> way.. it'll end up biting you eventually.
> 
> Anyway... we can speculate endlessly about non-existent language
> constructs, but I think we've probably done this one to death.
> -- 


Maybe no new language construct is needed:
just define that x.send() revives a generator.

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


Re: SMS api for python

2011-10-21 Thread Chris Rebert
On Fri, Oct 21, 2011 at 12:10 AM, Pankaj  wrote:
> I want to make an api that would recieve the SMS text from the user
> and process it then send the result back to the use. Is there any api
> that I can use to do this??

There would seem to be several options:
http://pypi.python.org/pypi?%3Aaction=search&term=sms&submit=search

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


Re: revive a generator

2011-10-21 Thread Yingjie Lan




- Original Message -
> From: Chris Angelico 
> To: [email protected]
> Cc: 
> Sent: Friday, October 21, 2011 4:27 PM
> Subject: Re: revive a generator
> 
> On Fri, Oct 21, 2011 at 7:02 PM, Yingjie Lan  wrote:
>>  What if the generator involves a variable from another scope,
>>  and before re-generating, the variable changed its value.
>>  Also, the generator could be passed in as an argument,
>>  so that we don't know its exact expression.
>> 
> 
> There's actually no way to know that the generator's even
> deterministic. Try this, for instance:
> 
  g=(input("Enter value %d or blank to stop: "%n) for n in 
> range(1,11))
  for s in g:
>     if not s: break
>     print("Processing input: "+s)
> 
> It may not be particularly useful, but it's certainly legal. And this
> generator cannot viably be restarted. 

Depends on what you want. If you want ten more inputs from user,
reviving this generator is certainly a good thing to do.

> The only way is to cast it to
> list first, but that doesn't work when you have to stop reading
> expressions from the generator part way.
> 
> What you could perhaps do is wrap the generator in something that
> saves its values:
> 
  class restartable(object):
>     def __init__(self,gen):
>         self.gen=gen
>         self.yielded=[]
>         self.iter=iter(self.yielded)
>     def restart(self):
>         self.iter=iter(self.yielded)
>     def __iter__(self):
>         return self
>     def __next__(self): # Remove the underscores for Python 2
>         try:
>             return self.iter.__next__()
>         except StopIteration:
>             pass
>         ret=self.gen.__next__()
>         self.yielded.append(ret)
>         return ret
> 
  h=restartable(g)
  for i in h:
>     if not i: break
>     print("Using: ",i)
  h.restart()
  for i in h:
>     if not i: break
>     print("Using: ",i)
> 
> Complicated, but what this does is returns a value from its saved list
> if there is one, otherwise returns a value from the original
> generator. It can be restarted as many times as necessary, and any
> time you read "past the end" of where you've read so far, the 
> original
> generator will be called upon.
> 
> Actually, this model might be useful for a repeatable random-number
> generator. But those are more efficiently restarted by means of
> reseeding the PRNG.
> 


Sure. Or you would like to have the next few random numbers with 
the same PRNG. 

These two cases seem to be strong use cases for reviving a generator.

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


No module named Pwd - under Apache 2.2

2011-10-21 Thread durumdara
Hi!

Win7/x64, Python 3.2, PyPGSQL f 3.2 and Apahce 2.2.

I created a script that working in CGI mode, it is read some table,
and returns with an XML.

It was working with normal mode, under Pyscripter, and under command
line.

But!

When I trying to use it from Apache 2.2 as cgi, I got the subjected
error:

"No module named Pwd"

I checked the code.
Everything is fine for the lines
import postgresql # this is working
con = postgresql.open() # this failed

Traceback (most recent call last):
File "C:/web/Apache2.2/cgi-bin/testpg.py", line 20, in Session
Function()
File "C:/web/Apache2.2/cgi-bin/testpg.py", line 38, in WebFunction db
= postgresql.open("pq://postgres:m@localhost/webdbdb")
File "C:\python32\lib\site-packages\postgresql\__init__.py", line 76,
in open std_params = _pg_param.collect(prompt_title = None)
File "C:\python32\lib\site-packages\postgresql\clientparameters.py",
line 620, in collect cpd =
normalize(extrapolate(chain(*d_parameters)))
File "C:\python32\lib\site-packages\postgresql\clientparameters.py",
line 563, in normalize for (k, v) in iter:
File "C:\python32\lib\site-packages\postgresql\clientparameters.py",
line 524, in extrapolate for item in iter:
File "C:\python32\lib\site-packages\postgresql\clientparameters.py",
line 130, in defaults user = getuser() or 'postgres'
File "C:\python32\lib\getpass.py", line 156, in getuser import pwd
ImportError: No module named pwd

The Apache is running under my account (normal user).
The sys.path is ok:
['C:\\web\\Apache2.2\\cgi-bin', 'C:\\Windows\\system32\\python32.zip',
'C:\\python32\\DLLs', 'C:\\python32\\lib', 'C:\\python32', 'C:\
\python32\\lib\\site-packages']

So we (me, and the postgresql's author) don't understand, why it
happens.

Any idea?

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


Re: No module named Pwd - under Apache 2.2

2011-10-21 Thread Peter Otten
durumdara wrote:

> Hi!
> 
> Win7/x64, Python 3.2, PyPGSQL f 3.2 and Apahce 2.2.
> 
> I created a script that working in CGI mode, it is read some table,
> and returns with an XML.
> 
> It was working with normal mode, under Pyscripter, and under command
> line.
> 
> But!
> 
> When I trying to use it from Apache 2.2 as cgi, I got the subjected
> error:
> 
> "No module named Pwd"

Remember that case matters in Python. Fortunately you included the 
traceback.
 
> I checked the code.
> Everything is fine for the lines
> import postgresql # this is working
> con = postgresql.open() # this failed
> 
> Traceback (most recent call last):
> File "C:/web/Apache2.2/cgi-bin/testpg.py", line 20, in Session
> Function()
> File "C:/web/Apache2.2/cgi-bin/testpg.py", line 38, in WebFunction db
> = postgresql.open("pq://postgres:m@localhost/webdbdb")
> File "C:\python32\lib\site-packages\postgresql\__init__.py", line 76,
> in open std_params = _pg_param.collect(prompt_title = None)
> File "C:\python32\lib\site-packages\postgresql\clientparameters.py",
> line 620, in collect cpd =
> normalize(extrapolate(chain(*d_parameters)))
> File "C:\python32\lib\site-packages\postgresql\clientparameters.py",
> line 563, in normalize for (k, v) in iter:
> File "C:\python32\lib\site-packages\postgresql\clientparameters.py",
> line 524, in extrapolate for item in iter:
> File "C:\python32\lib\site-packages\postgresql\clientparameters.py",
> line 130, in defaults user = getuser() or 'postgres'
> File "C:\python32\lib\getpass.py", line 156, in getuser import pwd
> ImportError: No module named pwd

The direct cause is that pwd is not available on Windows:

http://docs.python.org/dev/py3k/library/pwd.html
"""
33.2. pwd — The password database
Platforms: Unix
This module provides access to the Unix user account and password database. 
It is available on all Unix versions.
"""

The source of the failing function...

'''
def getuser():
"""Get the username from the environment or password database.

First try various environment variables, then the password
database.  This works on Windows as long as USERNAME is set.

"""

import os

for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
return user

# If this fails, the exception will "explain" why
import pwd
return pwd.getpwuid(os.getuid())[0]
'''

...suggests that you can make it work on Windows by setting the USERNAME  
environment variable (or any of the alternatives checked in the for-loop).

Does postgresql use the os user as a fallback for the database user? If so 
you might consider providing the database user explicitly.

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


Re: Problem with inheritance

2011-10-21 Thread Jean-Michel Pichavant

Sverre wrote:

I have to classes a  and b


class a(object):
def __init__(self,x):
self.x = x
self.build()

def build(self):
return

class b(a):
def __init__(self,x):
a.__init__(self,x)
self.y = 0  # ???

def build(self):
# do something
self.y += 2*self.x

 t = b(1)

The line marked with "???" will no be executed and I don't know the
reason. This example is working as intended, but not not the code I'm
working on. I'm using Eclipse. I don't know how to debug this
problem.

  


By the way, you're executing self.y += 2*self.x before initializing it to 0.

class b(a):
   def __init__(self,x):
   self.y = 0  
   a.__init__(self,x)



Note that having the constructor of 'a' calling an overriden method by 
'b' (build) is kinda funny. I would advise not to do so unless required.


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


Re: Benefit and belief

2011-10-21 Thread rusi
On Oct 21, 11:36 am, Ben Finney  wrote:
> rusi  writes:
> > The American programmer would profit more from learning Latin than
> > from learning yet another programming language.
>
> > Edsger Dijkstra in "On the fact that the Atlantic Ocean has two
> > sides"
>
> >http://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/EWD611.html
>
> It's ambiguous whether Dijkstra is saying anything positive about Latin
>  there.
>
> He could be saying “learning Latin would be a useful thing for average
> US programmers”.
>
> Or he could be saying “learning any second natural human language – even
> one as useless as Latin – will benefit the average US programmer more
> than learning another programming language”.
>
> I prefer to think someone as wise as Dijkstra would not be deluded as to
> the value of Latin, and lean more toward the latter meaning.

Well if you see the additional lines Chris has added or other personal
correspondences of EWD eg
http://digitalundivide.blogspot.com/2005/12/ewd-personal-reflection.html
Dijkstra clearly has a specific choice of latin.

It is easier to discount your view -- Dijkstra is wise -- than to deny
that Dijkstra was a devoted classicist -- music, languages and
ultimately programming.
And much bigger CSists than you and I -- eg Egon Borger, R W Hamming
etc -- have called Dijkstra a nut.

It seems to me that Dijkstra's quote would become a bit more
meaningful if one went up, so to speak, the class hierarchy.  He is
talking of 3 languages -- English, Latin and ones native tongue.
Generalizing (with slight inaccuracy) one could list 3 categories:

a communication language
b sacred/classical language
c mother tongue

Today a is singleton -- {English}
b is roughly {sanskrit, hebrew, arabic, latin, greek}
Each of these categories has a very different function just as Bach
and beatles have different functions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: revive a generator

2011-10-21 Thread Dave Angel

On 10/20/2011 10:09 PM, Yingjie Lan wrote:



What if the generator is passed in as an argument 
when you are writing a function? That is, the expression
is not available? 


Secondly, it would be nice to automatically revive it.
For example, when another for-statement or other
equivalent is applied to it.

Yingjie
That last point would definitely be incompatible.  It's quite useful to 
be able to peel some values off a generator, then use a for loop to get 
the remainder.  Simplest example I can think of would be to read a file 
where the first line(s) represent header information, and the body is 
obtainable with a simple loop.  I wouldn't be surprised if the csv 
module does that.


Not arguing whether an explicit revival is useful or not.  Although as 
others have pointed out, not all generators could accomplish it, and in 
some cases not unambiguously.



--

DaveA

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


Re: Py3K: file inheritance

2011-10-21 Thread Yosifov Pavel
On 21 окт, 13:50, Ian Kelly  wrote:
> On Thu, Oct 20, 2011 at 10:17 PM, Yosifov Pavel  wrote:
> > Little silly example:
>
> > class MyFile(file):
> > šdef __init__(self, *a, **ka):
> > š šsuper(MyFile, self).__init__(*a, **ka)
> > š šself.commented = 0
> > šdef write(self, s):
> > š šif s.startswith("#"):
> > š š šself.commented += 1
> > š š šsuper(MyFile, self).write(s)
>
> > When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then
> > to use MyFile (ex., open(name, mode, encoding), write(s)...) I get
> > errors like 'unsupported write' or AttributeError 'readable'... Can
> > you show me similar simple example like above but in Python 3.x?
>
> class MyTextIO(io.TextIOWrapper):
>     def __init__(self, *args, **kw):
>         super().__init__(*args, **kw)
>         self.commented = 0
>     def write(self, s):
>         if s.startswith('#'):
>             self.commented += 1
>             super().write(s)
>
> buffered = open(name, 'wb')
> textio = MyTextIO(buffered, encoding='utf-8')
> textio.write('line 1')
> textio.write('# line 2')
> textio.close()
> print(textio.commented)
>
> HTH,
> Ian

Thank you very much!
-- 
http://mail.python.org/mailman/listinfo/python-list


Automated form submissions

2011-10-21 Thread Matty Sarro
Hey everyone.
First, I apologize because I know this question has probably gotten
asked a lot. I am looking to automate filling out web forms, and no,
its not for spamming purposes.

I have looked at mechanize so far, but I'm not sure it quite fits what
I'm looking for. I know it can act as a browser and do some basic work
with forms, but I couldn't find anything in their documentation about
interacting with things like drop down boxes, etc.

Is selenium a better choice for this?
-Matt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: revive a generator

2011-10-21 Thread Steven D'Aprano
On Thu, 20 Oct 2011 19:09:42 -0700, Yingjie Lan wrote:

>> Here's an example of an explicit request to revive the generator:
> 
> 
>  g = (x*x for x in range(3))
>  for x in g: print x
>> 0
>> 1
>> 4
>  g = (x*x for x in range(3)) # revive the generator for x in g:
>  print x #now this will work
>> 0
>> 1
>> 4
>> 
>> ChrisA
> 
> 
> What if the generator is passed in as an argument when you are writing a
> function? That is, the expression is not available?

If the expression is not available, how do you expect to revive it? The 
expression is gone, it no longer exists. As you said in another post:

"What if the generator involves a variable from another scope,
and before re-generating, the variable changed its value."

Exactly. In general, you *can't* revive general iterators. It simply 
isn't possible. The variables that defined it might be gone. They might 
be non-deterministic: random numbers, data from the Internet or a file 
system that has changed, or user input. Trying to enforce the rule 
"iterators must support restarting" is foolish: it can't be done. You use 
an iterator when you want to iterate over something *once*, that is why 
they exist. If you want to iterate over it twice, don't use an iterator, 
use a sequence.

Forcing all iterators to save their data, on the off-chance that maybe 
somebody might want to iterate over it twice, defeats the purpose of an 
iterator.


> Secondly, it would be nice to automatically revive it. For example, when
> another for-statement or other equivalent is applied to it.

Nice? No, it would be horrible. It goes against the basic concept of an 
iterator: iterators should be memory efficient, generating values lazily. 
If you want an iterable sequence that you can iterate over multiple 
times, then use a list, or a custom iterable class.

If you want a socket wrench, use a socket wrench. Don't insist that 
hammers have to have a socket wrench attachment. 


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


Re: revive a generator

2011-10-21 Thread Ian Kelly
On Fri, Oct 21, 2011 at 2:02 AM, Yingjie Lan  wrote:
> Oops, my former reply has the code indentation messed up
> by the mail system. Here is a reformatted one:
>
>
> What if the generator involves a variable from another scope,
> and before re-generating, the variable changed its value.
> Also, the generator could be passed in as an argument,
> so that we don't know its exact expression.

In the former case, use a named generator function and call it twice
to create two generators.  In the latter case, don't pass in the
generator as an argument.  Pass in a callable that constructs the
iterator instead.  Modifying your example:

vo = 34
def mygen():
for x in range(3):
yield vo * x

def myfun(g):
global vo
for i in g(): print(i)
vo += 3
for i in g(): print(i)

myfun(mygen)

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


Re: IDLE lost from Windows menu !

2011-10-21 Thread c . fangeux
Thanks Alec.

For me it works with the following Default key :

"C:\Python32\pythonw.exe" "C:\Python32\Lib\idlelib\idle.pyw" -e "%1"

Otherwise IDLE does not open, only python was executed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automated form submissions

2011-10-21 Thread Grant Edwards
On 2011-10-21, Matty Sarro  wrote:

> First, I apologize because I know this question has probably gotten
> asked a lot. I am looking to automate filling out web forms, and no,
> its not for spamming purposes.

I use ClientForm for that, and I'm happy with it.

-- 
Grant Edwards   grant.b.edwardsYow! MERYL STREEP is my
  at   obstetrician!
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


non-standard module location (again)

2011-10-21 Thread Shane
Need to refine a question I asked earlier. If I have a module,

|--  foo
|---|
|---|---bar
|---|---|
|---|---|---__init__.py

then I can say import foo.bar

But suppose I want to import foo.bar.stuff and stuff isn't located on
under `bar' because it's user
supplied code:

|- stuff <- I want this to be logically
under foo.bar
|---|---__init__.py   <- even though it's not under bar in
the computer's file system

Now what: how to arrange to do command: import foo.bar.stuff
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: non-standard module location (again)

2011-10-21 Thread 88888 Dihedral
1. Define a new class with an instance of the foo class included so that one 
can use all foo's properties and add new attributes.

2. Derive a new class from foo that extends its properties with the  properties 
in foo accessible.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: non-standard module location (again)

2011-10-21 Thread Ian Kelly
On Fri, Oct 21, 2011 at 8:05 AM, Shane  wrote:
> Need to refine a question I asked earlier. If I have a module,
>
> |--  foo
> |---|
> |---|---bar
> |---|---|
> |---|---|---__init__.py
>
> then I can say import foo.bar
>
> But suppose I want to import foo.bar.stuff and stuff isn't located on
> under `bar' because it's user
> supplied code:
>
> |- stuff                             <- I want this to be logically
> under foo.bar
> |---|---__init__.py           <- even though it's not under bar in
> the computer's file system
>
> Now what: how to arrange to do command: import foo.bar.stuff

I've never tried this myself, but I think that pkgutil.extend_path is
what you're looking for.

http://docs.python.org/library/pkgutil.html

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


Re: fromutc: dt.tzinfo is not self: pytz.timezone('UTC').fromutc(datetime.utcnow())

2011-10-21 Thread aspineux
On Oct 19, 11:03 pm, Steven D'Aprano  wrote:
> On Wed, 19 Oct 2011 01:06:53 -0700, aspineux wrote:
> > hi
>
>  import pytz
>  from datetime import datetime
>  pytz.timezone('GMT0').fromutc(datetime.utcnow())
> > datetime.datetime(2011, 10, 19, 7, 54, 45, 579125, tzinfo= > 'GMT0'>)
>   pytz.timezone('UTC').fromutc(datetime.utcnow())
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > ValueError: fromutc: dt.tzinfo is not self
>  pytz.timezone('Europe/Brussels').fromutc(datetime.utcnow())
> > datetime.datetime(2011, 10, 19, 9, 55, 47, 787937, tzinfo= > 'Europe/Brussels' CEST+2:00:00 DST>)
>
> > Why does UTC fail ?
> > Bug or feature ?
>
> Looks like a bug to me. But I'm not an expert on pytz. Perhaps you should
> report it back to the package author.

Done

https://bugs.launchpad.net/pytz/+bug/879480

>
> --
> Steven

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


Re: non-standard module location (again)

2011-10-21 Thread Calvin Spealman
I am biased, but you could use a plugin loader like straight.plugin at
https://github.com/ironfroggy/straight.plugin

On Fri, Oct 21, 2011 at 10:05 AM, Shane  wrote:
> Need to refine a question I asked earlier. If I have a module,
>
> |--  foo
> |---|
> |---|---bar
> |---|---|
> |---|---|---__init__.py
>
> then I can say import foo.bar
>
> But suppose I want to import foo.bar.stuff and stuff isn't located on
> under `bar' because it's user
> supplied code:
>
> |- stuff                             <- I want this to be logically
> under foo.bar
> |---|---__init__.py           <- even though it's not under bar in
> the computer's file system
>
> Now what: how to arrange to do command: import foo.bar.stuff
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://techblog.ironfroggy.com/
Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: non-standard module location (again)

2011-10-21 Thread Steven D'Aprano
On Fri, 21 Oct 2011 07:05:32 -0700, Shane wrote:

> Need to refine a question I asked earlier. If I have a module,
> 
> |--  foo
> |---|
> |---|---bar
> |---|---|
> |---|---|---__init__.py
> 
> then I can say import foo.bar

No you can't, not the way you have listed it. As shown, foo is just a 
directory, so "import foo" will fail. However, "import bar" may work, 
provided foo/bar is in the module search path.

Perhaps you mean you have a package, with a sub-package:

foo/
+-- __init__.py
+-- bar/
... +-- __init__.py

Now you have TWO modules, foo and foo.bar, and you can "import foo.bar" 
successfully.


> But suppose I want to import foo.bar.stuff and stuff isn't located on
> under `bar' because it's user
> supplied code:
> 
> |- stuff <- I want this to be logically
> under foo.bar
> |---|---__init__.py   <- even though it's not under bar in
> the computer's file system

This is not clear what you are trying to do. Please explain more clearly 
what your module layout is.

foo/
+-- __init__.py
+-- stuff.py
+-- bar/
... +-- __init__.py


Or:

stuff.py
foo/
+-- __init__.py
+-- bar/
... +-- __init__.py


But since stuff is supposed to be a plugin, the most obvious, sensible 
way to lay out the modules would be:

foo/
+-- __init__.py
+-- plugins/
... +-- __init__.py
... +-- stuff.py
+-- bar/
... +-- __init__.py


and then "import foo.plugins.stuff". Clear, simple and obvious.


> Now what: how to arrange to do command: import foo.bar.stuff

Why do you want to call it foo.bar.stuff when it isn't actually 
foo.bar.stuff? Anyone trying to debug this will hate you, when they try 
to find a module foo/bar/stuff.py and can't find it because it doesn't 
exist.

If you must play games with module locations, put this inside the 
foo/bar/__init__.py module:

import foo.plugins.stuff as stuff

and now you can say "import foo.bar.stuff". But why bother?

Of course, plugin discovery is still a problem, but that's still a 
problem no matter what you do. Best to use a well-tested plugin library 
instead of trying to invent your own.



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


Re: how to change the order of a button, static text or other components

2011-10-21 Thread Ian Kelly
I assume you're arranging the components with a sizer.  Remove them from the
sizer, reinsert them in the order you want, and then call sizer.Layout().

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


Re: revive a generator

2011-10-21 Thread Terry Reedy
Here is a class that creates a re-iterable from any callable, such as a 
generator function, that returns an iterator when called, + captured 
arguments to be given to the function.


class reiterable():
  def __init__(self, itercall, *args, **kwds):
self.f = itercall  # callable that returns an iterator
self.args = args
self.kwds = kwds
  def __iter__(self):
return self.f(*self.args, **self.kwds)

def squares(n):
for i in range(n):
yield i*i

sq3 = reiterable(squares, 3)

for i in sq3: print(i)
for i in sq3: print(i)
>>>
0
1
4
0
1
4


--
Terry Jan Reedy

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


RE: how to change the order of a button, static text or other components

2011-10-21 Thread Prasad, Ramit
>what i want to do is,when i press a button, i change the order of
>selected components,how to do this?

This is so vague, I am tempted to think it is spambut on the chance it is 
not, I need a lot more information than you are providing to even attempt to 
give you any guidance.

1. By "button" do you mean keyboard/mouse or GUI; if you mean GUI button then 
what toolkit (Tk, wx, etc) are you referring to?
2. Define "selected components". How are they selected? What is a component?
3. Define "order" in regards to "components".

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


need python+windows edit control help

2011-10-21 Thread Eric S. Johansson
I'm back with yet another attempt at adding accessibility features using Python 
and NaturallySpeaking. I've simplified the concepts again and I really need some 
help from someone who knows Microsoft Windows and Python. My goal is developing 
a template for what I'm trying to do, then I can take over and generate some 
useful accessibility tools.


The core idea is an accessibility adjunct program receiving focus at 
start-of-utterance and returns focus to the original application at 
end-of-utterance. The window associated with the program contains a grid. Within 
the grid is an active cell which can accept input. Any cell could be made active 
depending on the state of the program but only one cell accepts input at any one 
time.


How would this be used? For example, the Skype IM window is atrocious for its 
disabled users. If one associated at two cell window accessibility adjunct 
program with Skype, the user could dictate, edit, retrain, etc. within the 
adjunct program and on command, return the data to Skype. One could also contain 
a small history so that like Skype, you could go back and edit a previously sent 
message.


a second use case is found on my blog http://blog.esjworks.com which is the tool 
to create mangled codenames from speech. I think the grid model works better 
than individual text fields that I originally wrote because it allows me to make 
better use of a cache of previously generated symbols.


Anyway, if anybody can help, I would really appreciate some assistance.

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


Re: compare range objects

2011-10-21 Thread SigmundV
On Oct 21, 2:55 am, Yingjie Lan  wrote:
>
> In simulation, one can use range objects to denote a discrete domain,
> and domain comparison could be very useful. Not just equality, but also
> things like if one domain is contained in another.

Can't sets [help(set)] be used for this?

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


Re: need python+windows edit control help

2011-10-21 Thread Mark Hammond

On 22/10/2011 10:30 AM, Eric S. Johansson wrote:

I'm back with yet another attempt at adding accessibility features using
Python and NaturallySpeaking. I've simplified the concepts again and I
really need some help from someone who knows Microsoft Windows and
Python. My goal is developing a template for what I'm trying to do, then
I can take over and generate some useful accessibility tools.


The [email protected] mailing list might be the best place to look 
for help - although you will probably need to provide much more 
information before anyone can help.  MSDN documents most of what you can 
do with edit control (look for windows messages starting with "EM_"), 
but without checking, I expect you will find programs like Skype don't 
use a Windows edit control at all.


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


Python on BlackBerry PlayBook

2011-10-21 Thread Peter Hansen
I'm slightly surprised to search and not see any recent mention of
Python running on the BlackBerry PlayBook.

Since the PlayBook simulators (for developers) were first available
late last year, they've contained Python 2.7. Some time before
release, the permissions were changed so the binaries weren't
accessible to developers or to apps.

There's now a developer beta of the upcoming 2.0 release of the
PlayBook's OS (built on QNX, previously named Tablet OS and now
rebranded as BBX).  Though this beta has almost none of the "user-
facing" improvements included, much of what's below the covers is
intact and probably fairly representative of how the final release
will look. In this beta 2.0 release, I see a full installation of
Python 3.2.1 (qnx6 build).  (The 2.7 install is still present, and
likely will remain for a long time, as it underpins some important
features in the OS.)

There are other clear signs that RIM/QNX have a significant chunk of
Python related work done already, including a video with some TAT user
interface demos ( 
http://www.youtube.com/watch?feature=player_embedded&v=Mia10Rekd0c
) where you can see (in 720P mode, around 3:30) files such as
Accelerometer.py and Horizon.py along with a "PyCascadesSDK".

Currently RIM has no public plans to make a Python SDK available to
developers for use in building PlayBook/BBX apps (which would include
the next generation of their phones). I believe if there were enough
interest shown, this situation could change.

So, I'm curious to what degree it would influence people's interest in
developing apps for the PlayBook if they were to provide a full Python
SDK, or even part of one which the community could flesh out, as one
of the development platforms available for the PlayBook.

For those not watching this area, the current set of platforms
includes native C/C++, WebWorks (HTML5/JavaScript and other web
standards), Java in the form of the now-beta Android player, and Adobe
AIR (Flash/ActionScript3).  I think Python would round that out very
nicely. ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


shutil _isindir

2011-10-21 Thread David Hoese

Hi,

I wasn't really sure where to post this since the python-dev list seems 
way too official.  I'm wondering/questioning the behavior of 
shutil.move.  It currently does a check for if the dst is inside the src 
directory with a _destinsrc function.  This function uses 
os.path.abspath to convert the arguments, but I think it should convert 
using os.path.realpath.  A recent problem I had with this I ended up 
asking on stackoverflow: 
http://stackoverflow.com/questions/7854608/python-shutil-move-odd-softlinking


So I was wondering if this sounds like a change that should happen in 
the shutil code or should programmers(me) just be more careful.  I feel 
like it should be in the shutil code since its getting around a checked 
case (destination inside source) and it can end up deleting information 
when a move was intended.  But then again this has been in the standard 
lib for a while now, so I'm guessing there are reasons for it...plus it 
was a dumb mistake by me.


So I guess what I'm asking is what are the reasons that _destinsrc uses 
abspath instead of realpath?  And is there a better place to ask this?


FYI, I was provided this link to the shutil.py source on SO: 
http://hg.python.org/cpython/file/d30482d51c25/Lib/shutil.py#l262


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


Re: need python+windows edit control help

2011-10-21 Thread Eric S. Johansson

On 10/21/2011 10:03 PM, Mark Hammond wrote:

On 22/10/2011 10:30 AM, Eric S. Johansson wrote:

I'm back with yet another attempt at adding accessibility features using
Python and NaturallySpeaking. I've simplified the concepts again and I
really need some help from someone who knows Microsoft Windows and
Python. My goal is developing a template for what I'm trying to do, then
I can take over and generate some useful accessibility tools.


The [email protected] mailing list might be the best place to look for 
help - although you will probably need to provide much more information before 
anyone can help.  MSDN documents most of what you can do with edit control 
(look for windows messages starting with "EM_"), but without checking, I 
expect you will find programs like Skype don't use a Windows edit control at all.


Mark
thanks for the pointer. When I talk about speech user interfaces in general and 
accessibility specifically, I find it's better to give a short overview (yes, 
this was short) before going into the details.  I'll be clearer about what kind 
of help I need.


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


Re: compare range objects

2011-10-21 Thread Steven D'Aprano
On Fri, 21 Oct 2011 16:42:16 -0700, SigmundV wrote:

> On Oct 21, 2:55 am, Yingjie Lan  wrote:
>>
>> In simulation, one can use range objects to denote a discrete domain,
>> and domain comparison could be very useful. Not just equality, but also
>> things like if one domain is contained in another.
> 
> Can't sets [help(set)] be used for this?

Sure. But the downside of sets is that, like lists, they are not lazy, 
they actually store every value in them rather than calculate them as 
needed, so they are only suitable for relatively small domains. Compare:

>>> sys.getsizeof(range())
20
>>> sys.getsizeof(set(range()))
262256

Now consider:

>>> sys.getsizeof(range(-9, 9))
20

Converted to a set, the memory requirements will be quite large, and the 
processing time to do anything useful with it likewise inflated.

If you need a data type to store large numeric domains, whether discrete 
or continuous, a tree of intervals storing the lower and upper bounds is 
probably the right solution.


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


Re: revive a generator

2011-10-21 Thread Steven D'Aprano
On Fri, 21 Oct 2011 16:25:47 -0400, Terry Reedy wrote:

> Here is a class that creates a re-iterable from any callable, such as a
> generator function, that returns an iterator when called, + captured
> arguments to be given to the function.
> 
> class reiterable():
>def __init__(self, itercall, *args, **kwds):
>  self.f = itercall  # callable that returns an iterator
>  self.args = args
>  self.kwds = kwds
>def __iter__(self):
>  return self.f(*self.args, **self.kwds)
> 
> def squares(n):
>  for i in range(n):
>  yield i*i
> 
> sq3 = reiterable(squares, 3)


We can do that even more simply, using a slightly different interface.

>>> from functools import partial
>>> sq3 = partial(squares, 3)

sq3 is now an iterator factory. You can't iterate over it directly, but 
it's easy to restart: just call it to return a fresh iterator.

>>> list(sq3())
[0, 1, 4]
>>> list(sq3())
[0, 1, 4]


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