Re: Import fails (newbie)

2010-06-18 Thread Peter Otten
mhorlick wrote:

> I'm a newbie and I have a small problem. After invoking IDLE -->
> 
> Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information.
 import os,glob
 os.chdir('D:/Python_Programs')
 print(os.getcwd())
> D:\Python_Programs
 print(glob.glob('*.*'))
> ['humansize.py', 'humansize.pyc']
 import humansize
> Traceback (most recent call last):
>   File "", line 1, in 
> import humansize
> ImportError: No module named humansize

> 
> In a DOS command window I have no problems with the program:
> 
>  Directory of D:\Python_Programs
> 
> 17/06/2010  01:56 PM  .
> 17/06/2010  01:56 PM  ..
> 17/06/2010  02:53 PM 1,266 humansize.py
> 17/06/2010  01:56 PM 1,315 humansize.pyc
>2 File(s)  2,581 bytes
>2 Dir(s)  104,122,085,376 bytes free
> 
> D:\Python_Programs>c:\python31\python humansize.py
> 1.0 TB
> 931.3 GiB
> 
> This 'humansize.py' program I got from the book 'Dive Into Python 3'.
> I don't know if you need to know the source.
> 
> Can someone explain why the 'import' fails?

If you run the same code from the command line it works. That's because the 
python interactive interpreter automatically includes the current directory 
into the search path for modules. When you are running Idle's shell you have 
to do that manually with

>>> import sys
>>> sys.path.insert(0, "")

I don't know if there is a reason for this difference or if it's just an 
omission.

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


Re: shelve / pickle error

2010-06-18 Thread Peter Otten
Vineet wrote:

> Hi !
> I am using python ver 2.6.5
> Trying to use shelve to save an object on the disc.
> =
> In the code
> # There are 'Person' & 'Manager' classes.
> # I created instance objects a,b,c from these classes.
> 
> from person import Person, Manager
> a = Person('A A')
> b = Person('B B', job = 'clerk', pay=5000)
> c = Manager('C C', 15000)
> 
> # instance objects a,b,c were created correctly.
> # then I store them on a shelve
> 
> import shelve
> dbs = shelve.open('mydb')
> for x in (a, b, c):
> dbs[x.name] = x
> dbs.close()
> 
> # On the disc, I can see the 3 files viz. mydb.dat, mydb.bak, mydb.dir
> # dbs.keys() is also giving me the correct list of keys.
> ==
> # NOW THE PROBLEM AREA ---
> # when I try to fetch an object by key---
> 
> a = dbs['A A']
> 
> # I get an error as--
> # File "F:\Py26\lib\shelve.py", line 122, in __getitem__
> # value = Unpickler(f).load()
> # ValueError: unsupported pickle protocol: 3
> =
> I couldn't locate the bug in this.
> Can anybody pl. point out?
> 
> ---Thanks,
> Vineet.

Have you saved the data using Python 3? Try loading it using Python 3, too.
You can also try explicitly specifying a protocol understood by both Python 
2 and 3, but I expect that you'll run into other incompatibilities.

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


Re: super() woes (n00b)

2010-06-18 Thread Jean-Michel Pichavant

Deadly Dirk wrote:

I cannot get right the super() function:
Python 3.1.1+ (r311:74480, Nov  2 2009, 14:49:22) 
[GCC 4.4.1] on linux2

Type "copyright", "credits" or "license()" for more information.
 No Subprocess 
  

class P:


def __init__(__class__,self):
print("I am a member of class P")


  

class C(P):


def __init__(self):
super().__init__(self)
print("I am a member of class C")




class P:
def __init__(self):
print("I am a member of class P")

class C(P):
def __init__(self):
super().__init__(self)
print("I am a member of class C")

x=C()

That is more or less the text from the "Quick Python Book". What am I 
doing wrong?


  
If you're quite new to Python I would advise to drop super and use an 
explicit call, sounds lame but my guess is that many people do that, 
'cause explicit >> implicit. Super is meant to solve some issues about 
multi inheritance, especially diamond diagram inheritance. It has no 
benefit for single inheritance.


I'm pretty sure someone will state that understanding super is pretty 
much easy once you've read the documenation but anticipating all the 
underlying concepts may be tricky. The only situation where super is 
absolutely required is when the inheritance diagram is built dynamically 
during execution.
Otherwise, I would say "Have the nuts to explicit which base class 
method you want to call" (easy for single inheritance though :) )


class C(P):
   def __init__(self):
  P.__init__(self)


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


Re: pythonize this!

2010-06-18 Thread Andre Alexander Bell
On 06/16/2010 12:47 PM, Lie Ryan wrote:
> Probably bending the rules a little bit:
> 
 sum(x**2 - 8*x - 20 for x in range(1, 2010, 5))
> 536926141

Bending them even further, the sum of the squares from 1 to N is given by

(1) N*(N+1)*(2*N+1)/6.

The given problem can be divided into five sums of every fifth square
starting from 1,2,3,4,5 respectively. This is given by

(2) S(a,k) = sum_{i=1}^k (5*i-4+a)^2

for a in range(5) and we are finally interested in

(3) S(k) = S(0,k) + S(1,k) + S(2,k) - S(3,k) - S(4,k)

Substituting (2) and (1) in (3) gives (in python code)

>>> S = lambda k: (50*k**3 - 165*k**2 - 47*k) / 6
>>> S(2010/5)
536926141

However, this only works for full cycles of (1,1,1,-1,-1) and you would
have to add/subtract the modulus parts yourself. (e.g. if you are
interested in your sum from 1..2011...

Cheers


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


variable variables

2010-06-18 Thread someone
Hello,

is it possible to make first attr variable?

some_object.attr.attr

so instead of attr I could use self.foo which has value "attr"



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


Re: pythonize this!

2010-06-18 Thread Stefan Behnel

Andre Alexander Bell, 18.06.2010 11:23:

On 06/16/2010 12:47 PM, Lie Ryan wrote:

Probably bending the rules a little bit:


sum(x**2 - 8*x - 20 for x in range(1, 2010, 5))

536926141


Bending them even further, the sum of the squares from 1 to N is given by

(1) N*(N+1)*(2*N+1)/6.

The given problem can be divided into five sums of every fifth square
starting from 1,2,3,4,5 respectively. This is given by

(2) S(a,k) = sum_{i=1}^k (5*i-4+a)^2

for a in range(5) and we are finally interested in

(3) S(k) = S(0,k) + S(1,k) + S(2,k) - S(3,k) - S(4,k)

Substituting (2) and (1) in (3) gives (in python code)


S = lambda k: (50*k**3 - 165*k**2 - 47*k) / 6
S(2010/5)

536926141

However, this only works for full cycles of (1,1,1,-1,-1) and you would
have to add/subtract the modulus parts yourself. (e.g. if you are
interested in your sum from 1..2011...


The thing is, if you can't do the math in the time that your processor 
needs to run the brute force loop, it's often not worth doing the math at all.


Stefan

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


Re: variable variables

2010-06-18 Thread Gabriel Genellina
En Fri, 18 Jun 2010 06:48:34 -0300, someone   
escribió:



is it possible to make first attr variable?

some_object.attr.attr

so instead of attr I could use self.foo which has value "attr"


I think you're looking for getattr:
http://docs.python.org/library/functions.html#getattr

name = "spam"
getattr(some_object, name) == some_object.spam == getattr(some_object,  
"spam")


--
Gabriel Genellina

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



Re: pythonize this!

2010-06-18 Thread Peter Otten
Stefan Behnel wrote:

> Andre Alexander Bell, 18.06.2010 11:23:
>> On 06/16/2010 12:47 PM, Lie Ryan wrote:
>>> Probably bending the rules a little bit:
>>>
>> sum(x**2 - 8*x - 20 for x in range(1, 2010, 5))
>>> 536926141
>>
>> Bending them even further, the sum of the squares from 1 to N is given by
>>
>> (1) N*(N+1)*(2*N+1)/6.
>>
>> The given problem can be divided into five sums of every fifth square
>> starting from 1,2,3,4,5 respectively. This is given by
>>
>> (2) S(a,k) = sum_{i=1}^k (5*i-4+a)^2
>>
>> for a in range(5) and we are finally interested in
>>
>> (3) S(k) = S(0,k) + S(1,k) + S(2,k) - S(3,k) - S(4,k)
>>
>> Substituting (2) and (1) in (3) gives (in python code)
>>
> S = lambda k: (50*k**3 - 165*k**2 - 47*k) / 6
> S(2010/5)
>> 536926141
>>
>> However, this only works for full cycles of (1,1,1,-1,-1) and you would
>> have to add/subtract the modulus parts yourself. (e.g. if you are
>> interested in your sum from 1..2011...
> 
> The thing is, if you can't do the math in the time that your processor
> needs to run the brute force loop, it's often not worth doing the math at
> all.

By that standard using Cython for the problem doesn't pay either;)

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


Re: super() woes (n00b)

2010-06-18 Thread Lie Ryan
On 06/18/10 19:19, Jean-Michel Pichavant wrote:
> Deadly Dirk wrote:
>> I cannot get right the super() function:
>> Python 3.1.1+ (r311:74480, Nov  2 2009, 14:49:22) [GCC 4.4.1] on linux2
>> Type "copyright", "credits" or "license()" for more information.
>>  No Subprocess 
>>  
> class P:
> 
>> def __init__(__class__,self):
>> print("I am a member of class P")
>>
>>  
> class C(P):
> 
>> def __init__(self):
>> super().__init__(self)
>> print("I am a member of class C")
>>
>>
>> class P:
>> def __init__(self):
>> print("I am a member of class P")
>>
>> class C(P):
>> def __init__(self):
>> super().__init__(self)
>> print("I am a member of class C")
>>
>> x=C()
>>
>> That is more or less the text from the "Quick Python Book". What am I
>> doing wrong?
>>
>>   
> If you're quite new to Python I would advise to drop super and use an
> explicit call, sounds lame but my guess is that many people do that,
> 'cause explicit >> implicit. Super is meant to solve some issues about
> multi inheritance, especially diamond diagram inheritance. It has no
> benefit for single inheritance.

Actually there is. If you need to anticipate the possibility of someone
else (or you in the future)  multiply-inheriting from your
singly-inheriting class, then your singly-inheriting class would need to
use super as well, otherwise the multiply-inheriting class might not be
properly initialized.

> I'm pretty sure someone will state that understanding super is pretty
> much easy once you've read the documenation but anticipating all the
> underlying concepts may be tricky. The only situation where super is
> absolutely required is when the inheritance diagram is built dynamically
> during execution.
> Otherwise, I would say "Have the nuts to explicit which base class
> method you want to call" (easy for single inheritance though :) )
> 
> class C(P):
>def __init__(self):
>   P.__init__(self)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List of lists surprising behaviour

2010-06-18 Thread bart.c

Benjamin Kaplan wrote:

On Thu, Jun 17, 2010 at 4:20 PM, bart.c  wrote:



I don't know how Python does things, but an object should either
specify a special way of duplicating itself, or lend itself to some
standard way of doing so. (So for a list, it's just a question of
copying the data in the list, then recursively duplicating each new
element..)



It's the recursively duplicating each element that's the problem. How
do you know when to stop?


When you reach a primitive object (one not comprising other objects). (I 
don't know if Python allows circular references, but that would give 
problems anyway: how would you even print out such a list?)


--
Bartc 


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


Re: pythonize this!

2010-06-18 Thread Stefan Behnel

Peter Otten, 18.06.2010 12:14:

Stefan Behnel wrote:


Andre Alexander Bell, 18.06.2010 11:23:

On 06/16/2010 12:47 PM, Lie Ryan wrote:

Probably bending the rules a little bit:


sum(x**2 - 8*x - 20 for x in range(1, 2010, 5))

536926141


Bending them even further, the sum of the squares from 1 to N is given by

(1) N*(N+1)*(2*N+1)/6.

The given problem can be divided into five sums of every fifth square
starting from 1,2,3,4,5 respectively. This is given by

(2) S(a,k) = sum_{i=1}^k (5*i-4+a)^2

for a in range(5) and we are finally interested in

(3) S(k) = S(0,k) + S(1,k) + S(2,k) - S(3,k) - S(4,k)

Substituting (2) and (1) in (3) gives (in python code)


S = lambda k: (50*k**3 - 165*k**2 - 47*k) / 6
S(2010/5)

536926141

However, this only works for full cycles of (1,1,1,-1,-1) and you would
have to add/subtract the modulus parts yourself. (e.g. if you are
interested in your sum from 1..2011...


The thing is, if you can't do the math in the time that your processor
needs to run the brute force loop, it's often not worth doing the math at
all.


By that standard using Cython for the problem doesn't pay either;)


True. Running the C compiler certainly takes a lot longer than starting up 
Python and running the loop.


Stefan

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


Re: variable variables

2010-06-18 Thread someone
On Jun 18, 12:01 pm, "Gabriel Genellina" 
wrote:
> En Fri, 18 Jun 2010 06:48:34 -0300, someone   
> escribió:
>
> > is it possible to make first attr variable?
>
> > some_object.attr.attr
>
> > so instead of attr I could use self.foo which has value "attr"
>
> I think you're looking for 
> getattr:http://docs.python.org/library/functions.html#getattr
>
> name = "spam"
> getattr(some_object, name) == some_object.spam == getattr(some_object,  
> "spam")

Thanks.

I was looking for a "short way" to do it because I have a lot
"some_object.attr.attr or some_object.other_attr.attr" in code. it
looks like I cannot replace attr with just other variable and must
type some_object.other_attr.attr or your solution which is however
longer to type :)

>
> --
> Gabriel Genellina

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


Re: variable variables

2010-06-18 Thread Lie Ryan
On 06/18/10 20:31, someone wrote:
> On Jun 18, 12:01 pm, "Gabriel Genellina" 
> wrote:
>> En Fri, 18 Jun 2010 06:48:34 -0300, someone   
>> escribió:
>>
>>> is it possible to make first attr variable?
>>
>>> some_object.attr.attr
>>
>>> so instead of attr I could use self.foo which has value "attr"
>>
>> I think you're looking for 
>> getattr:http://docs.python.org/library/functions.html#getattr
>>
>> name = "spam"
>> getattr(some_object, name) == some_object.spam == getattr(some_object,  
>> "spam")
> 
> Thanks.
> 
> I was looking for a "short way" to do it because I have a lot
> "some_object.attr.attr or some_object.other_attr.attr" in code. it
> looks like I cannot replace attr with just other variable and must
> type some_object.other_attr.attr or your solution which is however
> longer to type :)

Alternatively, if you have control over some_object class:

class SomeClass(object):
def __init__(self): pass
def __getattr__(self, attr):
return "attr: " + attr

some_object = SomeClass()

print some_object.foo
print some_object.myattr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List of lists surprising behaviour

2010-06-18 Thread Lie Ryan
On 06/18/10 20:00, bart.c wrote:
> (I
> don't know if Python allows circular references, but that would give
> problems anyway: how would you even print out such a list?)


Python uses ellipsis to indicate recursive list:

>>> a = [1, 2, 3]
>>> a.append(a)
>>> a
[1, 2, 3, [...]]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable variables

2010-06-18 Thread James Mills
On Fri, Jun 18, 2010 at 8:31 PM, someone  wrote:
> I was looking for a "short way" to do it because I have a lot
> "some_object.attr.attr or some_object.other_attr.attr" in code. it
> looks like I cannot replace attr with just other variable and must
> type some_object.other_attr.attr or your solution which is however
> longer to type :)

It would actually help to see some code.

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


constructing an object from another instance of the same class

2010-06-18 Thread Christoph Groth
Dear all,

sometimes it is handy to have a function which can take as argument
anything which can be converted into something, e.g.

def foo(arg):
arg = float(arg)
# ...

I would like to mimic this behavior of float for a user-defined type,
e.g. 

def bar(arg):
arg = My_type(arg)
# ...

Now I wonder what is the most pythonic way to write the __init__ method
of My_type?  The following comes to my mind:

class My_type:
def __init__(self, other):
if isinstance(other, type(self)):
self.a = other.a
self.b = other.b
return
# initialize self in some other way

It seems to me that in this way I might get problems when I pass an
instance of Derived_from_my_type to bar, as it will become an instance
of My_type.

What is a good way to express this?  In C++ (which I know better than
python) I would make bar accept a const reference to My_type.  Then I
could use it directly with instances of My_type, Derived_from_my_type
and other types which can be converted into My_type.

thanks
Christoph

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


Re: List of lists surprising behaviour

2010-06-18 Thread bart.c

Lie Ryan wrote:

On 06/18/10 20:00, bart.c wrote:

(I
don't know if Python allows circular references, but that would give
problems anyway: how would you even print out such a list?)



Python uses ellipsis to indicate recursive list:


a = [1, 2, 3]
a.append(a)
a

[1, 2, 3, [...]]


Ok, perhaps whatever logic print uses to know when to stop and show "...", 
can also be used by copy handlers...


(Although I have an issue with the way that that append works. I tried it in 
another, simpler language (which always does deep copies):


L:=(1,2,3)
L append:= L
print L

output:  (1,2,3,(1,2,3))

which is exactly what I'd expect, and not (1,2,3,(1,2,3,(1,2,3,...))) )

--
bartc 


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


Serialization, save type information in file and restore them

2010-06-18 Thread Timothy Wu
Hi,

I created a class that's able to manipulate tabulated data. I want to be
able to dump the bulk of the data and other attributes as a tab-delimited
text. I have trouble saving/restoring type information in the file. For
example, some attributes are int, others may be float, etc. So I want to
store the data type as well as the data value themselves in a file. And I
don't think I want to use Pickle because I want it to be readily opened in
vi and be readable as a tab-delimited file and be able to import into Excel
as well.

What's the best way to achieve this? I was able to write string like
"attribute = int(value)" into a file. But how do I get the value back? I
want the "int(value)" string to be loaded into the program and be executable
so I can actually create the instance variable in the class.

Any help appreciated, thanks.

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


MAKE UPTO $5000 MONTHLY! $2000 INYOUR FIRST 30 DAYS!

2010-06-18 Thread james
MAKE UP TO $5000 PER MONTH $2000 IN FIRST 30 DAYS

Generate $50 to $100 whenever you have a couple of hours free time
tospare.
You could make $50 or more in the next 2 hours. Starting right Now!
Today!
Awesome earnings get paid for your honest work
Join as a free member and get paid to your bank account
To join the Network follow the link

http://www.go-easy-money.com/home.html?a_aid=4c0be5bc81f9c

Get paid for your real work and earn awesome 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable variables

2010-06-18 Thread someone
On Jun 18, 12:49 pm, James Mills  wrote:
> On Fri, Jun 18, 2010 at 8:31 PM, someone  wrote:
> > I was looking for a "short way" to do it because I have a lot
> > "some_object.attr.attr or some_object.other_attr.attr" in code. it
> > looks like I cannot replace attr with just other variable and must
> > type some_object.other_attr.attr or your solution which is however
> > longer to type :)
>
> It would actually help to see some code.
>

here it is, In Foo I'd like to have instead of A self.type and the
same in class B

from some_module import some_object

class Foo:
def __init__(self):
self.type = 'A'

def printAttr(self):
some_object.A.B
some_object.A.C
some_object.A.D
some_object.A.E
some_object.A.F
some_object.A.G

class Bar:
def __init__(self):
self.type = 'B'

def printAttr(self):
some_object.B.B
some_object.B.C
some_object.B.D
some_object.B.E
some_object.B.F
some_object.B.G

> --James

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


Re: variable variables

2010-06-18 Thread Bruno Desthuilliers

someone a écrit :

On Jun 18, 12:49 pm, James Mills  wrote:

On Fri, Jun 18, 2010 at 8:31 PM, someone  wrote:

I was looking for a "short way" to do it because I have a lot
"some_object.attr.attr or some_object.other_attr.attr" in code. it
looks like I cannot replace attr with just other variable and must
type some_object.other_attr.attr or your solution which is however
longer to type :)

It would actually help to see some code.



here it is, In Foo I'd like to have instead of A self.type and the
same in class B

from some_module import some_object

class Foo:
def __init__(self):
self.type = 'A'

def printAttr(self):
some_object.A.B
some_object.A.C
some_object.A.D
some_object.A.E
some_object.A.F
some_object.A.G

class Bar:
def __init__(self):
self.type = 'B'

def printAttr(self):
some_object.B.B
some_object.B.C
some_object.B.D
some_object.B.E
some_object.B.F
some_object.B.G




from some_module import some_object

def print_attributes(obj, *attribs):
  for attr in attribs:
print getattr(obj, attr, None)

class Foo(object):
  type = 'A'

  def print_attr(self):
print_attributes(getattr(someobject, self.type), *"BCDEFG")

class Bar(Foo)
  type = 'B'


Still has a "code smell" thing to me, but hard to say not knowing the 
real code and context.

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


Re: variable variables

2010-06-18 Thread someone
On Jun 18, 2:05 pm, Bruno Desthuilliers  wrote:
> someone a crit :
>
>
>
>
>
> > On Jun 18, 12:49 pm, James Mills  wrote:
> >> On Fri, Jun 18, 2010 at 8:31 PM, someone  wrote:
> >>> I was looking for a "short way" to do it because I have a lot
> >>> "some_object.attr.attr or some_object.other_attr.attr" in code. it
> >>> looks like I cannot replace attr with just other variable and must
> >>> type some_object.other_attr.attr or your solution which is however
> >>> longer to type :)
> >> It would actually help to see some code.
>
> > here it is, In Foo I'd like to have instead of A self.type and the
> > same in class B
>
> > from some_module import some_object
>
> > class Foo:
> >     def __init__(self):
> >         self.type = 'A'
>
> >     def printAttr(self):
> >         some_object.A.B
> >         some_object.A.C
> >         some_object.A.D
> >         some_object.A.E
> >         some_object.A.F
> >         some_object.A.G
>
> > class Bar:
> >     def __init__(self):
> >         self.type = 'B'
>
> >     def printAttr(self):
> >         some_object.B.B
> >         some_object.B.C
> >         some_object.B.D
> >         some_object.B.E
> >         some_object.B.F
> >         some_object.B.G
>
> from some_module import some_object
>
> def print_attributes(obj, *attribs):
>    for attr in attribs:
>      print getattr(obj, attr, None)
>
> class Foo(object):
>    type = 'A'
>
>    def print_attr(self):
>      print_attributes(getattr(someobject, self.type), *"BCDEFG")
>
> class Bar(Foo)
>    type = 'B'
>
> Still has a "code smell" thing to me, but hard to say not knowing the
> real code and context.

sorry, code is not about printing variables rather accessing, it's
just example.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: constructing an object from another instance of the same class

2010-06-18 Thread Bruno Desthuilliers

Christoph Groth a écrit :

Dear all,

sometimes it is handy to have a function which can take as argument
anything which can be converted into something, e.g.

def foo(arg):
arg = float(arg)
# ...

I would like to mimic this behavior of float for a user-defined type,
e.g. 


def bar(arg):
arg = My_type(arg)
# ...

Now I wonder what is the most pythonic way to write the __init__ method
of My_type?  The following comes to my mind:

class My_type:
def __init__(self, other):
if isinstance(other, type(self)):
self.a = other.a
self.b = other.b
return
# initialize self in some other way

It seems to me that in this way I might get problems when I pass an
instance of Derived_from_my_type to bar, as it will become an instance
of My_type.


The instance you pass to bar won't "become" anything else. You create a 
new My_type instance from the Derived_from_my_type one's values, and 
rebinding the _local_ name 'arg' only affects the local namespace.



BTW, the convention in Python is to use TitleCase for class names 
(except - for historical reasons - for most builtin types which are 
lowercase).




What is a good way to express this?


Depends on what are the possible initializers / arguments for My_type. 
There are a few possible solutions but which one is best depends on the 
concrete case and personal tastes.


 In C++ 


Forget about C++ - Python is a different beast !-)


(which I know better than
python) I would make bar accept a const reference to My_type.  Then I
could use it directly with instances of My_type, Derived_from_my_type
and other types which can be converted into My_type.


If you only worry about being able to use any "My_type like" object - 
that is, any object implementing a given subset of My_type's interface, 
then just document your expectations in the function's docstring and use 
whatever object is passed in as if it was a My_type instance. Period. As 
long as you document what your function expects, it's the caller's 
responsaibility to make sure it provides something compatible. If he 
don't, well he'll get a nice traceback.


I know this might look very freestyle and a bit frightening when coming 
from one of these B&D languages, but that's really the Python way, and 
from experience, it JustWork(tm).

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


Re: variable variables

2010-06-18 Thread Bruno Desthuilliers

someone a écrit :

On Jun 18, 2:05 pm, Bruno Desthuilliers  wrote:

(snip)


Still has a "code smell" thing to me, but hard to say not knowing the
real code and context.


sorry, code is not about printing variables rather accessing, it's
just example.


Yeps, this I understood - hence the  "but..." part of the sentence. What 
I dislike the most here is the obj.otherobj.yetanother.attrib stuff - 
might be ok in this case but it's an obvious violation of the law of 
Demeter (=> AKA: only talk to your neighbour).


But anyway - if Foo only needs to know about someobject.A and Bar only 
needs to know about someobject.B, then resolve them once:



from some_module import some_object

class Foo:
def __init__(self):
self.type = 'A'

def printAttr(self):
target = getattr(someobject, self.type)
target.B
target.C
target.D
# etc...


This will also save a couple useless lookups. In fact, aliasing a 
commonly accessed attribute (or method) to a local name is an old time 
Python micro-optimization.


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


Re: The inverse of .join

2010-06-18 Thread Neil Cerutti
On 2010-06-18, Steven D'Aprano  wrote:
> On Thu, 17 Jun 2010 20:03:42 +, Neil Cerutti wrote:
>> I'm currently using the following without problems, while
>> reading a data file. One of the fields is a comma separated
>> list, and may be empty.
>> 
>>   f = rec['codes']
>>   if f == "":
>> f = []
>>   else:
>> f = f.split(",")
>> 
>> I just wondered if something smoother was available.
>
> Seems pretty smooth to me. What's wrong with it? I assume
> you've put it into a function for ease of use and reduction of
> code duplication.

The part that's wrong with it, and it's probably my fault, is
that I can never think of it. I had to go dig it out of my code
to remember what the special case was.

> You could also use the ternary operator, in which case it's a
> mere two- liner and short enough to inline wherever you need
> it:
>
> f = rec['codes']
> f = f.split(",") if f else []

That's pretty cool.

Thanks to everybody for their thoughts.

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


Re: super() woes (n00b)

2010-06-18 Thread Deadly Dirk
On Thu, 17 Jun 2010 12:18:33 -0700, Ethan Furman wrote:

> Deadly Dirk wrote:
>> On Thu, 17 Jun 2010 13:48:45 -0400, J. Cliff Dyer wrote:
>> 
>>> super gives you an instantiated version of the super class, which
>>> means that you don't have to explicitly send self to any methods you
>>> call on it.
>>>
>>> So use `super().__init__()` instead.
>> 
>> Thanks. Interestingly enough, it works in Python 3, which is what the
>> book is about. It doesn't work in Python 2.6
> 
> as Thomas Jollans said days ago:
>  > but you should really install Python 3.1 (it's in ubuntu, as others
>  > have said!) because you will almost certainly hit into other snags.
> 
> or, as Gabriele Lanaro said in that same thread:
>  > else take a book that covers python 2.x syntax
> 
> Cut-and-pasting-ly yours,
> 
> ~Ethan~

As you can see, I followed the advice and installed the latest Python.



-- 
I don't think, therefore I am not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: super() woes (n00b)

2010-06-18 Thread Deadly Dirk
On Fri, 18 Jun 2010 11:19:56 +0200, Jean-Michel Pichavant wrote:

> Deadly Dirk wrote:
>> I cannot get right the super() function: Python 3.1.1+ (r311:74480, Nov
>>  2 2009, 14:49:22) [GCC 4.4.1] on linux2
>> Type "copyright", "credits" or "license()" for more information. 
>> No Subprocess 
>>   
> class P:
> 
>> def __init__(__class__,self):
>> print("I am a member of class P")
>>
>>
>> 
> class C(P):
> 
>> def __init__(self):
>> super().__init__(self)
>> print("I am a member of class C")
>>
>>
>> 
>> class P:
>> def __init__(self):
>> print("I am a member of class P")
>>
>> class C(P):
>> def __init__(self):
>> super().__init__(self)
>> print("I am a member of class C")
>>
>> x=C()
>>
>> That is more or less the text from the "Quick Python Book". What am I
>> doing wrong?
>>
>>
> If you're quite new to Python I would advise to drop super and use an
> explicit call, sounds lame but my guess is that many people do that,
> 'cause explicit >> implicit. Super is meant to solve some issues about
> multi inheritance, especially diamond diagram inheritance. It has no
> benefit for single inheritance.
> 
> I'm pretty sure someone will state that understanding super is pretty
> much easy once you've read the documenation but anticipating all the
> underlying concepts may be tricky. The only situation where super is
> absolutely required is when the inheritance diagram is built dynamically
> during execution.
> Otherwise, I would say "Have the nuts to explicit which base class
> method you want to call" (easy for single inheritance though :) )
> 
> class C(P):
> def __init__(self):
>P.__init__(self)
> 
> 
> JM

Jean-Michel, thanks for your advice. I do think that I understand the 
"super" function, I used to do some C++ programming and am quite adept at 
programming. I am learning Python and, as a stickler for details, I am 
testing and running every little piece of code.




-- 
I don't think, therefore I am not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MAKE UPTO $5000 MONTHLY! $2000 INYOUR FIRST 30 DAYS!

2010-06-18 Thread Vannia Rajan
On Fri, Jun 18, 2010 at 4:50 PM, james  wrote:

> MAKE UP TO $5000 PER MONTH $2000 IN FIRST 30 DAYS
> ...
> Get paid for your real work and earn awesome 
>

I hope the List administrator has noticed this misuse.

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


Re: pythonize this!

2010-06-18 Thread Mark Lawrence

On 18/06/2010 10:23, Andre Alexander Bell wrote:

On 06/16/2010 12:47 PM, Lie Ryan wrote:

Probably bending the rules a little bit:


sum(x**2 - 8*x - 20 for x in range(1, 2010, 5))

536926141


Bending them even further, the sum of the squares from 1 to N is given by

(1) N*(N+1)*(2*N+1)/6.

The given problem can be divided into five sums of every fifth square
starting from 1,2,3,4,5 respectively. This is given by

(2) S(a,k) = sum_{i=1}^k (5*i-4+a)^2

for a in range(5) and we are finally interested in

(3) S(k) = S(0,k) + S(1,k) + S(2,k) - S(3,k) - S(4,k)

Substituting (2) and (1) in (3) gives (in python code)


S = lambda k: (50*k**3 - 165*k**2 - 47*k) / 6
S(2010/5)

536926141

However, this only works for full cycles of (1,1,1,-1,-1) and you would
have to add/subtract the modulus parts yourself. (e.g. if you are
interested in your sum from 1..2011...

Cheers


Andre


The good news is that this is easily the fastest piece of code that I've 
seen yet.  The bad news is that first prize in the speed competition is 
a night out with me. :)


Cheers.

Mark Lawrence.

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


Re: variable variables

2010-06-18 Thread someone
On Jun 18, 2:37 pm, Bruno Desthuilliers  wrote:
> someone a crit :
>
> > On Jun 18, 2:05 pm, Bruno Desthuilliers  > [email protected]> wrote:
> (snip)
>
> >> Still has a "code smell" thing to me, but hard to say not knowing the
> >> real code and context.
>
> > sorry, code is not about printing variables rather accessing, it's
> > just example.
>
> Yeps, this I understood - hence the  "but..." part of the sentence. What
> I dislike the most here is the obj.otherobj.yetanother.attrib stuff -
> might be ok in this case but it's an obvious violation of the law of
> Demeter (=> AKA: only talk to your neighbour).
>
> But anyway - if Foo only needs to know about someobject.A and Bar only
> needs to know about someobject.B, then resolve them once:
>
> from some_module import some_object
>
> class Foo:
>      def __init__(self):
>          self.type = 'A'
>
>      def printAttr(self):
>          target = getattr(someobject, self.type)
>         target.B
>          target.C
>          target.D
>          # etc...
>
> This will also save a couple useless lookups. In fact, aliasing a
> commonly accessed attribute (or method) to a local name is an old time
> Python micro-optimization.

Thanks, this looks good. I've missed point that self.type must be an
instance of object and not just some string :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable variables

2010-06-18 Thread Jean-Michel Pichavant

someone wrote:

On Jun 18, 12:49 pm, James Mills  wrote:
  

On Fri, Jun 18, 2010 at 8:31 PM, someone  wrote:


I was looking for a "short way" to do it because I have a lot
"some_object.attr.attr or some_object.other_attr.attr" in code. it
looks like I cannot replace attr with just other variable and must
type some_object.other_attr.attr or your solution which is however
longer to type :)
  

It would actually help to see some code.




here it is, In Foo I'd like to have instead of A self.type and the
same in class B

from some_module import some_object

class Foo:
def __init__(self):
self.type = 'A'

def printAttr(self):
some_object.A.B
some_object.A.C
some_object.A.D
some_object.A.E
some_object.A.F
some_object.A.G

class Bar:
def __init__(self):
self.type = 'B'

def printAttr(self):
some_object.B.B
some_object.B.C
some_object.B.D
some_object.B.E
some_object.B.F
some_object.B.G

  

--James



  


Here is a way to to do it. Note that it is quite dangereous 'cause you 
may confuse everyone by accessing some_object attributes like a Foo 
attributes. Basically, when the attributes is not found in the Foo 
namespace, it will use the some_object.A or some_object.B namespace instead.



some_object = Bar()
some_object.A = Bar()
some_object.B = Bar()
some_object.A.bar = 'I come from A'
some_object.B.bar = 'I come from B'

class Foo(object):

   def __init__(self, _type):
  self.type = _type

   def __getattribute__(self, name):
  try:
  return object.__getattribute__(self, name)
  except AttributeError:
  return getattr(getattr(some_object, self.type), name)

   def __setattr__(self, name, value):
   try:
   # first look if self has the attribute, if so set it
   if object.__getattribute__(self, name):
   return object.__setattr__(self, name, value)
   except AttributeError:
   # look into some_object
   try:
   _type = object.__getattribute__(self, 'type')
   if hasattr(getattr(some_object, _type), name):
   return setattr(getattr(some_object, _type), name, value)
   except AttributeError:
   pass
   # attribute neither found in self nor in some_object, let's 
create it in self

   return object.__setattr__(self, name, value)

fa = Foo('A')
fb = Foo('B')

print fa.bar
> I come from A

print fb.bar
> I come from B

fa.bar = 'hello world'

print some_object.A.bar
> hello world



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


Re: constructing an object from another instance of the same class

2010-06-18 Thread Christoph Groth
Bruno Desthuilliers  writes:

>> It seems to me that in this way I might get problems when I pass an
>> instance of Derived_from_my_type to bar, as it will become an
>> instance of My_type.
>
> The instance you pass to bar won't "become" anything else. You create
> a new My_type instance from the Derived_from_my_type one's values, and
> rebinding the _local_ name 'arg' only affects the local namespace.

I understand that it won't become an instance of My_type globally.  But
it will become locally and this breaks polymorphism.  (See code example
I provide at the end)

>>  In C++
>
> Forget about C++ - Python is a different beast !-)

Still, it is useful and interesting to compare languages.  Like in the
real world it is also insightful to compare the grammar of quite
different languages.

>> (which I know better than python) I would make bar accept a const
>> reference to My_type.  Then I could use it directly with instances of
>> My_type, Derived_from_my_type and other types which can be converted
>> into My_type.
>
> If you only worry about being able to use any "My_type like" object -
> that is, any object implementing a given subset of My_type's
> interface, then just document your expectations in the function's
> docstring and use whatever object is passed in as if it was a My_type
> instance. Period. As long as you document what your function expects,
> it's the caller's responsaibility to make sure it provides something
> compatible. If he don't, well he'll get a nice traceback.

This is not what I am worrying about.  I will try to be more explicit.

I would like to have a class for a "special matrix".  This is an
ordinary 2n by 2n matrix which can be thought of as consisting of four n
by n sized blocks.

At this moment, I just use normal numpy arrays (or anything which
behaves like them).  But I have very good reasons to actually have a
class for these special matrices.  Still, I would like to be able to
call functions which work with "special matrices" with plain numpy
arrays as arguments.  In that case, the arguments which are plain
matrices should be converted to "special" ones such that the main part
of the function can assume to always work with "special matrices".

The code attached in the end (which is a complete runnable script)
should illustrate what I mean.

This example works as I want except that when bar is called with a an
argument of type Derived, it behaves as Base.  Also, I am not sure
whether there is a nicer way to achieve the following functionality for
Base.__init__:

If other is of type Base already, just "pass it on".  Otherwise,
construct an instance of Base from it.


import numpy as np

class Base:
def __init__(self, other):
if isinstance(other, type(self)):
self = other
return
n = other.shape[0]
assert n == other.shape[1]
assert n % 2 == 0
n //= 2
self.a = other[0 : n, 0 : n]
self.b = other[n : 2*n, 0 : n]
self.c = other[0 : n, n : 2*n]
self.d = other[n : 2*n, n : 2*n]

def hello(self):
print 'hello from Base'

class Derived(Base):
def hello(self):
print 'hello from Derived'

def bar(arg):
arg = Base(arg)
# Do something useful with arg.{a..d}
arg.hello()

# This works.
a = np.identity(4)
bar(a)

# And this also.
a = Base(np.identity(4))
bar(a)

# But this prints "hello from Base"!
a = Derived(np.identity(4))
bar(a)

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


Re: super() woes (n00b)

2010-06-18 Thread Jean-Michel Pichavant

Deadly Dirk wrote:

On Fri, 18 Jun 2010 11:19:56 +0200, Jean-Michel Pichavant wrote:

  

Deadly Dirk wrote:


I cannot get right the super() function: Python 3.1.1+ (r311:74480, Nov
 2 2009, 14:49:22) [GCC 4.4.1] on linux2
Type "copyright", "credits" or "license()" for more information. 
No Subprocess 
  
  

class P:



def __init__(__class__,self):
print("I am a member of class P")



  

class C(P):



def __init__(self):
super().__init__(self)
print("I am a member of class C")



class P:

def __init__(self):
print("I am a member of class P")

class C(P):
def __init__(self):
super().__init__(self)
print("I am a member of class C")

x=C()

That is more or less the text from the "Quick Python Book". What am I
doing wrong?


  

If you're quite new to Python I would advise to drop super and use an
explicit call, sounds lame but my guess is that many people do that,
'cause explicit >> implicit. Super is meant to solve some issues about
multi inheritance, especially diamond diagram inheritance. It has no
benefit for single inheritance.

I'm pretty sure someone will state that understanding super is pretty
much easy once you've read the documenation but anticipating all the
underlying concepts may be tricky. The only situation where super is
absolutely required is when the inheritance diagram is built dynamically
during execution.
Otherwise, I would say "Have the nuts to explicit which base class
method you want to call" (easy for single inheritance though :) )

class C(P):
def __init__(self):
   P.__init__(self)


JM



Jean-Michel, thanks for your advice. I do think that I understand the 
"super" function, I used to do some C++ programming and am quite adept at 
programming. I am learning Python and, as a stickler for details, I am 
testing and running every little piece of code.


  
Quote from a c++ forum "There is no way (IMO) to generally refer to the 
superclass in C++ because of multiple inheritance".
Python super funtion is different from the Java's one, (there's no 
multiple inheritance in Java if I'm not wrong).


Think about this :

   A
  /  \
 B   C
  \  /
   D

python 2.5 code:

class A(object):
   def foo(self):
   print 'I am A'

class B(A):
   def foo(self):
   super(B, self).foo()
   print 'I am B'

class C(A):
   def foo(self):
   super(C, self).foo()
   print 'I am C'

class D(B,C):
   def foo(self):
   super(D, self).foo()
   print 'I am D'

d = D()
d.foo()

What would you expect as a result ? Diffcult to say at first glance.

JM

PS : answer is
I am A
I am C
I am B
I am D

As you can see, super() is *not* the superclass otherwise 'I am A' 
should have appeared twice (superclass method of B and C).



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


Re: pythonize this!

2010-06-18 Thread Steven D'Aprano
On Fri, 18 Jun 2010 14:32:30 +0100, Mark Lawrence wrote:

> The good news is that this is easily the fastest piece of code that I've
> seen yet.  The bad news is that first prize in the speed competition is
> a night out with me.

I suppose second prize is two nights out with you?


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


Re: List of lists surprising behaviour

2010-06-18 Thread Steven D'Aprano
On Fri, 18 Jun 2010 12:07:38 +0100, bart.c wrote:

> (Although I have an issue with the way that that append works. I tried
> it in another, simpler language (which always does deep copies):
> 
> L:=(1,2,3)
> L append:= L
> print L
> 
> output:  (1,2,3,(1,2,3))
> 
> which is exactly what I'd expect, 
> and not (1,2,3,(1,2,3,(1,2,3,...))) )

I find that behaviour a big surprise. You asked to append the list L, not 
a copy of the list L. So why is this "simpler" language making a copy 
without being asked?

If you asked for:

L:=(1,2,3)
M:=(0,1)
M append:= L

does it also append a copy of L instead of L? If so, how do you append 
the original rather than wastefully making a copy? If L is huge, making a 
copy before appending will be slow, and potentially fail.



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


Re: constructing an object from another instance of the same class

2010-06-18 Thread Bruno Desthuilliers

Christoph Groth a écrit :

Bruno Desthuilliers  writes:


It seems to me that in this way I might get problems when I pass an
instance of Derived_from_my_type to bar, as it will become an
instance of My_type.

The instance you pass to bar won't "become" anything else. You create
a new My_type instance from the Derived_from_my_type one's values, and
rebinding the _local_ name 'arg' only affects the local namespace.


I understand that it won't become an instance of My_type globally.  But
it will become locally and this breaks polymorphism.


Then don't do it !-)


 (See code example
I provide at the end)


 In C++

Forget about C++ - Python is a different beast !-)


Still, it is useful and interesting to compare languages.


Indeed. But you have to understand enough of a language to compare it 
with another one. The old "I can write C in any language" syndrom...




(which I know better than python) I would make bar accept a const
reference to My_type.  Then I could use it directly with instances of
My_type, Derived_from_my_type and other types which can be converted
into My_type.

If you only worry about being able to use any "My_type like" object -
that is, any object implementing a given subset of My_type's
interface, then just document your expectations in the function's
docstring and use whatever object is passed in as if it was a My_type
instance. Period. As long as you document what your function expects,
it's the caller's responsaibility to make sure it provides something
compatible. If he don't, well he'll get a nice traceback.


This is not what I am worrying about.  I will try to be more explicit.


Ok.


I would like to have a class for a "special matrix".  This is an
ordinary 2n by 2n matrix which can be thought of as consisting of four n
by n sized blocks.


Right.


At this moment, I just use normal numpy arrays (or anything which
behaves like them).  But I have very good reasons to actually have a
class for these special matrices.  Still, I would like to be able to
call functions which work with "special matrices" with plain numpy
arrays as arguments.  In that case, the arguments which are plain
matrices should be converted to "special" ones such that the main part
of the function can assume to always work with "special matrices".


Ok. So you want to build a "special matrice" like object from the numpy 
array.



The code attached in the end (which is a complete runnable script)
should illustrate what I mean.

This example works as I want except that when bar is called with a an
argument of type Derived, it behaves as Base.


Ok.


 Also, I am not sure
whether there is a nicer way to achieve the following functionality for
Base.__init__:

If other is of type Base already, just "pass it on".  Otherwise,
construct an instance of Base from it.


You can't do this in the initializer, you have to use either a factory 
function or the proper constructor (or an alternate constructor).




import numpy as np

class Base:


If you're using Python 2.x, make this:

class Base(object):


def __init__(self, other):
if isinstance(other, type(self)):
self = other


'self' is a local name. Rebinding a local name only impact the local 
namespace.



return
n = other.shape[0]
assert n == other.shape[1]
assert n % 2 == 0
n //= 2
self.a = other[0 : n, 0 : n]
self.b = other[n : 2*n, 0 : n]
self.c = other[0 : n, n : 2*n]
self.d = other[n : 2*n, n : 2*n]



Question : is there any case where you may want to instanciate this 
class with explicit values for a, b, c and d ?



Anyway: the simplest solution here is to replace the call to your Base 
class with a call to a factory function. I'd probably go for something 
like (Q&D untested code and other usual warnings) :


class Base(object):
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d

   @classmethod
   def from_array(cls, arr):
   """ alternate constructor from a numpy array """
   n = arr.shape[0]
   assert n == arr.shape[1]
   assert n % 2 == 0
   n //= 2
   return cls(
  arr[0 : n, 0 : n],
  arr[n : 2*n, 0 : n],
  arr[0 : n, n : 2*n],
  arr[n : 2*n, n : 2*n]
  )


def hello(self):
print 'hello from Base'


class Derived(Base):
def hello(self):
print 'hello from Derived'

def coerce(obj, cls=Base):
if isinstance(obj, cls):
return obj
else:
return cls.from_array(obj)


def bar(arg):
arg = coerce(arg)
# Do something useful with arg.{a..d}
arg.hello()

# This works.
a = np.identity(4)
bar(a)

# And this also.
a = Base.from_array(np.identity(4))
bar(a)

# And now this should work too
a = Derived.from_array(np.identity(4))
bar(a)



Does it solve your problem ?-)


Note that if using a plain function hurts your feeli

Re: constructing an object from another instance of the same class

2010-06-18 Thread Bruno Desthuilliers

Bruno Desthuilliers a écrit :

Christoph Groth a écrit :

Bruno Desthuilliers  writes:


(snip)

 In C++

Forget about C++ - Python is a different beast !-)


Still, it is useful and interesting to compare languages.


Indeed. But you have to understand enough of a language to compare it 
with another one. The old "I can write C in any language" syndrom...


Re-reading this it might looks a bit patronizing. Sorry, was not my 
intention at all - it was just a general consideration (I mean "mostly 
useless blah").


(snip)
--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonize this!

2010-06-18 Thread Mark Lawrence

On 18/06/2010 16:00, Steven D'Aprano wrote:

On Fri, 18 Jun 2010 14:32:30 +0100, Mark Lawrence wrote:


The good news is that this is easily the fastest piece of code that I've
seen yet.  The bad news is that first prize in the speed competition is
a night out with me.


I suppose second prize is two nights out with you?




Stephen, you are absolutely correct.  I never realised from your posting 
history just how astute you are. :)


Kindest regards.

Mark Lawrence.

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


Re: constructing an object from another instance of the same class

2010-06-18 Thread Stephen Hansen
On 6/18/10 3:51 AM, Christoph Groth wrote:
> sometimes it is handy to have a function which can take as argument
> anything which can be converted into something, e.g.
[snip]
> I would like to mimic this behavior of float for a user-defined type,
> e.g. 
[snip]
> Now I wonder what is the most pythonic way to write the __init__ method
> of My_type?  The following comes to my mind:
[snip]
> It seems to me that in this way I might get problems when I pass an
> instance of Derived_from_my_type to bar, as it will become an instance
> of My_type.
[snip]
> What is a good way to express this?  In C++ (which I know better than
> python) I would make bar accept a const reference to My_type.  Then I
> could use it directly with instances of My_type, Derived_from_my_type
> and other types which can be converted into My_type.

This kind of polymorphism is anti-Pythonic; you don't go around
converting an object from one 'type' to another 'type' like that, and
especially not for that reason.

Basically, you're thinking about *types* too much. They are much less
important in Python then they are in C++; you achieve polymorphism in
Python by matching behavior and following the protocols of the other type.

Duck typing: if it quacks like a duck, its a duck.

The Pythonic way to approach the problem of, "I want to accept anything
which can be converted into X" is to accept the variable, and then
simply *use* it *as if* it were X. If the value implemented the
appropriate protocols (say, __add__ and __radd__ and friends and such if
you want it to mimic a numeric type) then it will work.

For all intents and purposes, it *is* X, for all you need to worry about.

If it doesn't implement the protocols, then it will error out, yes.
It'll throw an exception. You can be prepared to catch such exceptions
and say, log an error, "Expected value to be a numeric type", or you can
just let it propagate (I almost always prefer this method). Sometimes
you need to be a little more careful, sometimes less: but generally,
only at the boundry of your program do you need to worry about
type-correctness (i.e., where user and data is accepted, you have to
convert stuff there.) Anywhere else, its a bug if you pass the wrote
thing in: unit tests and exceptions/tracebacks are excellent for finding
and fixing such bugs.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: constructing an object from another instance of the same class

2010-06-18 Thread Steven D'Aprano
On Fri, 18 Jun 2010 16:30:00 +0200, Christoph Groth wrote:

> If other is of type Base already, just "pass it on".  Otherwise,
> construct an instance of Base from it.
> 
>  import
> numpy as np
> 
> class Base:
> def __init__(self, other):
> if isinstance(other, type(self)):
> self = other
> return

This does not do what you think it does. I wonder whether you've actually 
tried it?

>>> import numpy as np
>>> a = np.identity(4)
>>> b = Base(a)  # works
>>> c = Base(b)  # doesn't work
>>> b.a
array([[ 1.,  0.],
   [ 0.,  1.]])
>>> c.a
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: Base instance has no attribute 'a'


In your __init__ method, the line:

self = other

does NOT do what you think. All it does is re-bind the name "self" to 
refer to the other object, while leaving the instance untouched. 
Consequently, the rest of the initialisation code never gets executed and 
your instance is uninitialised.

To do what you are trying to do, you need to do two things:

(1) Use a new-style class, not a classic (old-style) class; and

(2) Use the constructor __new__ and not the initialiser __init__.

And then you should change your mind and not do it, because you will be 
opening a huge can of horrible bugs that will be really hard to debug. 
The reason being, your class is *mutable*, and you will find yourself 
having code where you think you have two different instances but you 
actually only have one instance with two different names.

Here's a simple example demonstrating why this is a bad idea:


>>> class Recycler(object):
... def __new__(cls, other):
... if isinstance(other, cls):
... return other
... else:
... instance = super(Recycler, cls).__new__(cls, other)
... return instance
... def __init__(self, other):
... # Don't re-initialise when self has been recycled.
... if self is other:
... return
... self.attr = other
...
>>> a = Recycler(42)
>>> a.attr
42
>>> b = Recycler(a)
>>> b.attr
42
>>> b.attr = 23
>>> a.attr
23


a and b are the same object, and whatever you do to one, you do to the 
other. Object constructors should construct new instances, not give you 
back an existing instance which is already in use elsewhere.

However, if you make the class *immutable*, then it is perfectly safe, 
because you can't modify immutable objects and therefore it doesn't 
matter whether a and b refer to two different instances or the same 
instance. For example, Python caches small integers and reuses them, as a 
memory optimization:

>>> a = int("42")
>>> b = int("42")
>>> a is b
True

but doesn't bother for larger integers to avoid filling the cache will 
billions of ints that will never be re-used:

>>> a = int("4200207")
>>> b = int("4200207")
>>> a is b
False

This is safe, since you can't change the value of the object 42. (You can 
rebind the name "a", but not modify the object itself.)

So, to recap:

* you aren't doing what you think you're doing;

* even if you were, you shouldn't;

* unless you make the class immutable.



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


Re: pythonize this!

2010-06-18 Thread Andre Alexander Bell
On 06/18/2010 03:32 PM, Mark Lawrence wrote:
> The good news is that this is easily the fastest piece of code that I've
> seen yet.  The bad news is that first prize in the speed competition is
> a night out with me. :)

Well, that actually means that Stefan Behnel will run my solution
through cython. As Steven D'Aprano already pointed out this then will
make me receive the second price of two nights out?

Cheers


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


Re: The inverse of .join

2010-06-18 Thread Jon Clements
On 17 June, 21:03, Neil Cerutti  wrote:
> On 2010-06-17, Robert Kern  wrote:
>
> > On 6/17/10 2:08 PM, Neil Cerutti wrote:
> >> On 2010-06-17, Ian Kelly  wrote:
> >>> On Thu, Jun 17, 2010 at 11:45 AM, Neil Cerutti
> >>>   wrote:
>  What's the best way to do the inverse operation of the .join
>  function?
>
> >>> Use the str.split method?
>
> >> split is perfect except for what happens with an empty string.
>
> > Why don't you try it and find out?
>
> I'm currently using the following without problems, while reading
> a data file. One of the fields is a comma separated list, and may
> be empty.
>
>   f = rec['codes']
>   if f == "":
>     f = []
>   else:
>     f = f.split(",")
>
> I just wondered if something smoother was available.
>
> --
> Neil Cerutti

In terms of behaviour and 'safety', I'd go for:

>>> rec = { 'code1': '1,2,3', 'code2': '' }
>>> next(csv.reader([rec['code1']]))
['1', '2', '3']
>>> next(csv.reader([rec['code2']]))
[]

hth
Jon.

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


Re: List of lists surprising behaviour

2010-06-18 Thread bart.c


"Steven D'Aprano"  wrote in message
news:[email protected]...

On Fri, 18 Jun 2010 12:07:38 +0100, bart.c wrote:


(Although I have an issue with the way that that append works. I tried
it in another, simpler language (which always does deep copies):

L:=(1,2,3)
L append:= L
print L

output:  (1,2,3,(1,2,3))

which is exactly what I'd expect,
and not (1,2,3,(1,2,3,(1,2,3,...))) )


I find that behaviour a big surprise. You asked to append the list L, not
a copy of the list L. So why is this "simpler" language making a copy
without being asked?

If you asked for:

L:=(1,2,3)
M:=(0,1)
M append:= L

does it also append a copy of L instead of L?


It make a copy.


If so, how do you append
the original rather than wastefully making a copy?


I don't think it can, without perhaps doing something with explicit
pointers.


If L is huge, making a
copy before appending will be slow, and potentially fail.


I don't know whether L append:=L requires 3 times the space of L, or 2
times, during the operation. But it should be doable using just twice the
space.

I suppose there are pros and cons to both approaches; copying all the time
at least avoids some of the odd effects and inconsistencies you get using
Python:

a1=[1,2,3]
a1.append(a1)

a2=[1,2,3]
b=[1,2,3]
a2.append(b)

a3=[1,2,3]
a3.append([1,2,3])

print ("a1 = ",a1)
print ("a2 = ",a2)
print ("a3 = ",a3)

Here, a1 ends up with a different result from a2, a3, even though the same
value is being appended to the same list of numbers in each case. And it 
might sometimes bite you in the arse as the OP demonstrated:


L=[1,2,3]
M=[0,1]
M.append(L)

print (M) # output: [0, 1, [1, 2, 3]]

L[1]=31416

print (M) # output: [0, 1, [1, 31416, 3]], yikes!

--
Bartc


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


cannot get html content of tag with BeautifulSoup

2010-06-18 Thread someone
Hello,

does anyone know how to get html contents of an tag with
BeautifulSoup? In example I'd like to get all html which is in first
 tag, i.e. This is paragraph one. as
unicode object

p.contents gives me a list which I cannot join TypeError: sequence
item 0: expected string, Tag found

Thanks!


from BeautifulSoup import BeautifulSoup
import re

doc = ['Page title',
   'This is
paragraph one.',
   'This is paragraph two.',
   '']
soup = BeautifulSoup(''.join(doc))
#print soup.prettify()
r = re.compile(r'<[^<]*?/?>')
for i, p in enumerate(soup.findAll('p')):
#print type(p) #
#print type(p.contents) #list
content = "".join(p.contents) #fails

p_without_html = r.sub(' ', content)
print p_without_html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running a program from another program.

2010-06-18 Thread Laurent Verweijen
Op donderdag 17-06-2010 om 15:16 uur [tijdzone -0700], schreef Stephen
Hansen: 
> On 6/17/10 3:06 PM, Laurent Verweijen wrote:
> >>
> >> In your other thread you include an actual traceback:
> >>
> >> Traceback (most recent call last):
> >>   File "subchronous_test.py", line 5, in 
> >> send_all(str(p), n)
> >>   File "/home/Somelauw/asynchronous.py", line 145, in send_all
> >> while len(data):
> >> TypeError: object of type 'int' has no len()
> >>
> >> The first argumetn to send_all should be the actual Popen subclass. The
> >> second should be a string to send. I think that line really is intended
> >> to be:
> >>
> >> send_all(p, str(n)) # assuming 'n' is say, the number 5.
> >>
> > 
> > You are right, I swapped the parameters, but even if I correct it, it
> > still gives the second error.
> > 
> 
> General rule of thumb: its best to never use the word "still" when it
> comes to debugging Python and exceptions, unless you are absolutely
> certain the exception is precisely the same.
> 
> I don't doubt that you may still get an exception on send_all; but there
> is no way you're getting the *same* exception (that specific type error:
> attempting to call len() on an integer) if you corrected your arguments.
> 
> You're getting the EOFError, because you're never sending anything to
> the subprocess. You're not getting anything from the subprocess because
> it never receives anything to send back. And apparently there's an error
> on send, which is causing that problem, but that error is...?
>
My last post, contains the output after I fixed swapping the parameters
and everything you said.

I think there is still a problem with output that gets blocked.
Couldn't it be just that the output which gets blocked is causing this
error?

Anyway here is the output again:

python subchronous_test.py




Traceback (most recent call last):
  File "increment.py", line 8, in 
n = int(raw_input(str(n))) + 1
EOFError: EOF when reading a line

close failed in file object destructor:
Error in sys.excepthook:

Original exception was:



And here are all 3 files concatenated:

# subchronous_test
import sys
from asynchronous import *
p = Popen(["python", "increment.py"], stdin=PIPE, stdout=PIPE, stderr =
sys.stderr)

for n in [5, 7, 10, 4]:
send_all(p, str(n))
print(recv_some(p))


# increment.py
import sys, traceback

try:
n = 0
while True:
n = int(raw_input(str(n))) + 1
except:
print >>sys.stderr, traceback.format_exc()


# asynchronous.py
## {{{ http://code.activestate.com/recipes/440554/ (r10)
import os
import subprocess
import errno
import time
import sys

PIPE = subprocess.PIPE

if subprocess.mswindows:
from win32file import ReadFile, WriteFile
from win32pipe import PeekNamedPipe
import msvcrt
else:
import select
import fcntl

class Popen(subprocess.Popen):
def recv(self, maxsize=None):
return self._recv('stdout', maxsize)

def recv_err(self, maxsize=None):
return self._recv('stderr', maxsize)

def send_recv(self, input='', maxsize=None):
return self.send(input), self.recv(maxsize),
self.recv_err(maxsize)

def get_conn_maxsize(self, which, maxsize):
if maxsize is None:
maxsize = 1024
elif maxsize < 1:
maxsize = 1
return getattr(self, which), maxsize

def _close(self, which):
getattr(self, which).close()
setattr(self, which, None)

if subprocess.mswindows:
def send(self, input):
if not self.stdin:
return None

try:
x = msvcrt.get_osfhandle(self.stdin.fileno())
(errCode, written) = WriteFile(x, input)
except ValueError:
return self._close('stdin')
except (subprocess.pywintypes.error, Exception), why:
if why[0] in (109, errno.ESHUTDOWN):
return self._close('stdin')
raise

return written

def _recv(self, which, maxsize):
conn, maxsize = self.get_conn_maxsize(which, maxsize)
if conn is None:
return None

try:
x = msvcrt.get_osfhandle(conn.fileno())
(read, nAvail, nMessage) = PeekNamedPipe(x, 0)
if maxsize < nAvail:
nAvail = maxsize
if nAvail > 0:
(errCode, read) = ReadFile(x, nAvail, None)
except ValueError:
return self._close(which)
except (subprocess.pywintypes.error, Exception), why:
if why[0] in (109, errno.ESHUTDOWN):
return self._close(which)
raise

if self.universal_newlines:
read = self._translate_newlines(read)
return read

else:
def send(self, input):
if not self.stdin:
retu

Re: The inverse of .join

2010-06-18 Thread Neil Cerutti
On 2010-06-18, Jon Clements  wrote:
>> I just wondered if something smoother was available.
>
> In terms of behaviour and 'safety', I'd go for:
>
 rec = { 'code1': '1,2,3', 'code2': '' }
 next(csv.reader([rec['code1']]))
> ['1', '2', '3']
 next(csv.reader([rec['code2']]))
> []

Slick!

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


Re: pythonize this!

2010-06-18 Thread Mark Lawrence

On 18/06/2010 16:26, Andre Alexander Bell wrote:

On 06/18/2010 03:32 PM, Mark Lawrence wrote:

The good news is that this is easily the fastest piece of code that I've
seen yet.  The bad news is that first prize in the speed competition is
a night out with me. :)


Well, that actually means that Stefan Behnel will run my solution
through cython. As Steven D'Aprano already pointed out this then will
make me receive the second price of two nights out?

Cheers


Andre


Andre, looks like a really bad day for you then, *TWO* nights out with 
me *AND* (looking at your email address) Germany loosing in the world 
cup. :(


Kindest regards.

Mark Lawrence.

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


Re: cannot get html content of tag with BeautifulSoup

2010-06-18 Thread someone
On Jun 18, 5:41 pm, someone  wrote:
> Hello,
>
> does anyone know how to get html contents of an tag with
> BeautifulSoup? In example I'd like to get all html which is in first
>  tag, i.e. This is paragraph one. as
> unicode object
>
> p.contents gives me a list which I cannot join TypeError: sequence
> item 0: expected string, Tag found
>
> Thanks!
>
> from BeautifulSoup import BeautifulSoup
> import re
>
> doc = ['Page title',
>        'This is
> paragraph one.',
>        'This is paragraph two. p>',
>        '']
> soup = BeautifulSoup(''.join(doc))
> #print soup.prettify()
> r = re.compile(r'<[^<]*?/?>')
> for i, p in enumerate(soup.findAll('p')):
>     #print type(p) #
>     #print type(p.contents) #list
>     content = "".join(p.contents) #fails
>
>     p_without_html = r.sub(' ', content)
>     print p_without_html

p.renderContents() was what I've looked for
-- 
http://mail.python.org/mailman/listinfo/python-list


using subprocess.Popen does not suppress terminal window on Windows

2010-06-18 Thread Steven
I am calling a ruby program from a python gui and using
subprocess.Popen in Windows XP using python 2.6.  Unfortunately,
whenever the ruby program is called a blank command window appears on
screen, annoying my users.  Is there a way to suppress this behaviour?

Below is a minimal program that demonstrates the problem.  The problem
does not manifest if the python program is launched via the command
line.  To duplicate launch from Windows Explorer by double-clicking on
the python file.

--- call_double.pyw ---
from subprocess import *
import time

time.sleep(3) # to show that command window is result of call to Popen
p = Popen(['ruby.exe', 'double.rb'], stdin=PIPE, stdout=PIPE,
stderr=PIPE)
results = open('results.txt', 'w')
for n in range(10):
p.stdin.write("%d\n" % n)
result = p.stdout.readline().strip()
results.write('double(%s) => %2s\n' % (n, result))
results.close()

--- end of call_double.pyw ---

--- double.rb ---
while true
puts $stdin.gets().strip!.to_i * 2
STDOUT.flush
end
--- end of double.rb ---

thanks for any help,
Steven Rumbalski
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using subprocess.Popen does not suppress terminal window on Windows

2010-06-18 Thread Alf P. Steinbach

* Steven, on 18.06.2010 18:23:

I am calling a ruby program from a python gui and using
subprocess.Popen in Windows XP using python 2.6.  Unfortunately,
whenever the ruby program is called a blank command window appears on
screen, annoying my users.  Is there a way to suppress this behaviour?


Yes, launch the GUI subsystem Ruby interpreter.



C:\projects\blog\cppx\exception_translation\examples> set pathe
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.CJS;.JS;.JSE;.WSF;.WSH;.RB;.RBW

C:\projects\blog\cppx\exception_translation\examples> assoc .rb
.rb=rbFile

C:\projects\blog\cppx\exception_translation\examples> ftype rbfile
rbfile="C:\progra...@utilities\ruby\bin\ruby.exe" "%1" %*

C:\projects\blog\cppx\exception_translation\examples> assoc .rbw
.rbw=rbwFile

C:\projects\blog\cppx\exception_translation\examples> ftype rbwfile
rbwfile="C:\progra...@utilities\ruby\bin\rubyw.exe" "%1" %*

C:\projects\blog\cppx\exception_translation\examples> _



OK, it's called 'rubyw.exe'.

You can read about console and GUI subsystem for the complete beginner 
programmer at http://tinyurl.com/programmingbookP3>, ch. 1 (hope I got the 
URL right).




Below is a minimal program that demonstrates the problem.  The problem
does not manifest if the python program is launched via the command
line.  To duplicate launch from Windows Explorer by double-clicking on
the python file.

--- call_double.pyw ---
from subprocess import *
import time

time.sleep(3) # to show that command window is result of call to Popen
p = Popen(['ruby.exe', 'double.rb'], stdin=PIPE, stdout=PIPE,
stderr=PIPE)


Change this to 'rubyw.exe' when running in Windows.

Note that that it's perfectly OK to pipe to or from a GUI subsystem program.



results = open('results.txt', 'w')
for n in range(10):
 p.stdin.write("%d\n" % n)
 result = p.stdout.readline().strip()
 results.write('double(%s) =>  %2s\n' % (n, result))
results.close()

--- end of call_double.pyw ---

--- double.rb ---
while true
 puts $stdin.gets().strip!.to_i * 2
 STDOUT.flush
end



Cheers & hth.,

- Alf

--
blog at http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list


Re: List of lists surprising behaviour

2010-06-18 Thread Stephen Hansen
On 6/18/10 8:40 AM, bart.c wrote:
> I suppose there are pros and cons to both approaches; copying all the time
> at least avoids some of the odd effects and inconsistencies you get using
> Python:

What inconsistencies? All your examples are perfectly consistent. Its
just consistent to different ideals. Python never copies implicitly; and
every object you create has a concrete identity in and of itself,
utterly separate from its potential equality.

> a1=[1,2,3]
> a1.append(a1)

The "a1" object is a distinct object unto itself; you are appending said
distinct object onto the end of itself. Entirely doable, even if you
don't usually want to. Recursive, but doable if that's what you want. If
you wished to append a copy, you must-- as always, consistently--
explicitly copy it.

I.e.,

a1.append(a1[:])

> a2=[1,2,3]
> b=[1,2,3]
> a2.append(b)

a2 is a distinct object from b; that the two objects are equal means
nothing. So you're appending an object to the end of a2 which happens to
be equal to it.

> a3=[1,2,3]
> a3.append([1,2,3])

This is just another way of writing the previous example; that in one
you are naming the object [1,2,3] and in the other you are not, doesn't
mean anything. A named vs unnamed object in Python behaves exactly the same.

> print ("a1 = ",a1)
> print ("a2 = ",a2)
> print ("a3 = ",a3)
> 
> Here, a1 ends up with a different result from a2, a3, even though the same
> value is being appended to the same list of numbers in each case. 

There's the rub: the VALUE is not being appended. The *actual object* is.

Consider:

>>> print a1 is a2
False

> And it
> might sometimes bite you in the arse as the OP demonstrated:
> 
> L=[1,2,3]
> M=[0,1]
> M.append(L)
> 
> print (M) # output: [0, 1, [1, 2, 3]]
> 
> L[1]=31416
> 
> print (M) # output: [0, 1, [1, 31416, 3]], yikes!

That might bite you on your arse if you think Python implicitly copies;
but since the rule is very simple -- it /never/ implicitly copies -- and
that it objects are discrete entities and not just names of certain
values, it more likely then not will be beneficial to you quite often
down the road. You'll -want- that to be how things work. Eventually.
When you learn more Python.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jewish Pirates of the Caribbean

2010-06-18 Thread Mick

George Neuner DESERVES his FREEDOM OF SPEECH.

Freedom of speech dousn't guarantee an audience 
--
http://mail.python.org/mailman/listinfo/python-list


creating application specific files?

2010-06-18 Thread muhannad shubita
hello there, how can i create a new file type and associate it with a
program, for example create a type like .XXX file and give it the
application icon, and when double-clicked on the file the application
runs

[windows platform]

help is appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


catching my own exception

2010-06-18 Thread nick
I have a problem with catching my own exception. Here is the code:
http://fly.srk.fer.hr/~nick/travapi/blame.php?repname=Travian+API&path=%2Fvillage.py&;

Line 252 calls a method, which on line 207 raises a
SomethingBeingBuiltError exception. On line 253 I catch that
exception, but when I run that code, I get:

Traceback (most recent call last):
  File "village.py", line 252, in 
v.upgrade_cheapest()
  File "/media/data/home/code/travapi/village.py", line 207, in upgrade_cheapest
raise SomethingBeingBuiltError()
village.SomethingBeingBuiltError: 'Unable to upgrade, check if something is 
being built.'

If I change line 253 to only "except:", everything works as
expected. How come? What am I missing? Any help would be appreciated.

P.S.: I'm aware I'm exposing my login/pass in the code. Don't care
really, those are throwaway accounts.

-- 
"Now the storm has passed over me
I'm left to drift on a dead calm sea
And watch her forever through the cracks in the beams
Nailed across the doorways of the bedrooms of my dreams"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating application specific files?

2010-06-18 Thread MRAB

muhannad shubita wrote:
hello there, how can i create a new file type and associate it with a 
program, for example create a type like .XXX file and give it the 
application icon, and when double-clicked on the file the application 
runs
 
[windows platform]
 
help is appreciated.



In Window Explorer, go to Tools->Folder Options, and then the File Types
tab.
If you mean programmatically, read about ASSOC:

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/assoc.mspx?mfr=true

and FTYPE:

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ftype.mspx?mfr=true

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


i18n for applications and modules

2010-06-18 Thread Hans-Joachim Widmaier
Internationalizing Python applications is not really hard, and there are 
some useful how-tos available for the beginner.


I've written several (still smallish) applications and localized them.
Although it works, it has some rather inelegant areas or rough edges 
that keep nagging me.


1. Python itself is not really ready for i18n. Some modules, like 
optparse (or argparse in 2.7) create user-visible messages, but are not 
prepared for localization. Since I needed to add some functionality to 
optparse anyways, I've done the i18n, too. IMHO not nice.


2. What's the preferred way if you use several modules (your own) that 
are reused in other applications? Put '_' in the __builtins__ namespace,
use it in your modules and make one message catalog? Plus: fairly easy 
to do. Minus: you keep translating the same things over and over again, 
and you still need some armor in front of every module so you can import 
it, e.g., in the interactive interpreter. My armor looks like this:


def NullTranslation(x):
return x
try:
_("works when not standalone")
except NameError:
import __builtins__
__builtins__.__dict__['_'] = NullTranslation

Or create a message catalog for every module and setup the gettext 
machinery at the start of every module? Plus: modules must be translated 
only once, changes in a module do not require all your applications 
where it is used to be updated with new translations.
Minus: if your application is cross-platform, and you make it nice for 
Windows users with py2exe, you may get into trouble helping your modules 
find their message catalogs. At least I had severe problems doing it.


Quoting the Zen:

"There should be one-- and preferably only one --obvious way to do it."

I haven't found this way yet.

I'd like to know how others cope with these problems. Maybe I'm just 
missing the obviuos.


--
Hans-Joachim Widmaier
--
http://mail.python.org/mailman/listinfo/python-list


Re: creating application specific files?

2010-06-18 Thread Stephen Hansen
On 6/18/10 10:03 AM, muhannad shubita wrote:
> hello there, how can i create a new file type and associate it with a
> program, for example create a type like .XXX file and give it the
> application icon, and when double-clicked on the file the application
> runs

This has nothing to do with Python.

http://letmegoogleforyou.com/?q=how+to+associate+files+in+windows

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


announcing jsonutil package

2010-06-18 Thread Zooko O'Whielacronx
Folks:

I've uploaded a small package to PyPI which is a small wrapper around
simplejson that sets the default behavior so that JSON decimal values
are mapped to type Decimal instead of type float:

http://pypi.python.org/pypi/jsonutil

It has pretty thorough unit tests, including a copy of all the
simplejson unit tests, which I copied into the jsonutil package, as
well as a few added tests to test the new functionality. I also did
some benchmarks to satisfy myself that using jsonutil isn't noticeably
slower than using simplejson. You can find the benchmarking code in
the package, but I'm not sure if it comes with documentation
sufficient to let you easily run the benchmarks yourself.

I did this originally on behalf of my employer, SimpleGeo, who now use
this wrapper in our production system.

Based on my reasoning and also SimpleGeo's experience, this introduced
absolutely no compatibility problems between our service (an HTTP API)
and users of our service, who themselves parse and construct JSON
however they want (typically from other languages like Ruby and PHP).
This is because no user of our API sends a string like "0.03" and then
expects to get back "0.02" and breaks in some way if
we instead send back "0.03".

If there were clients like that, then they would have broken when we
made this change, because formerly, using simplejson, we would have
accepted "0.03" and then sent back "0.02", but now,
using jsonutil, we accept "0.03" and send back "0.03".

I would expect clients that breaks in such a case to be rare, but of
course computer systems are always surprising me with their creative
ways to be fragile and failure-prone, so I wouldn't bet against a few
such systems existing. If anyone spots one in the wild, please let me
know.

Converting from simplejson (default float) to jsonutil (default
Decimal) did, as expected, cause type mismatches internally inside our
server, where some calling code was expecting float and the called
code was returning Decimal, or vice versa. So far these problems were
all "shallow" in that they could be fixed by adding a cast or by
changing one side or the other, as desired.

In short, I advise people not to fear using Python Decimals to manage
their JSON decimal strings. It will probably introduce zero
incompatibilities across the wire, and any type mismatches it
introduces within your own code base will probably be easy to fix.

Regards,

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


Re: catching my own exception

2010-06-18 Thread Jon Clements
On 18 June, 18:08, nick  wrote:
> I have a problem with catching my own exception. Here is the 
> code:http://fly.srk.fer.hr/~nick/travapi/blame.php?repname=Travian+API&pat...
>
> Line 252 calls a method, which on line 207 raises a
> SomethingBeingBuiltError exception. On line 253 I catch that
> exception, but when I run that code, I get:
>
> Traceback (most recent call last):
>   File "village.py", line 252, in 
>     v.upgrade_cheapest()
>   File "/media/data/home/code/travapi/village.py", line 207, in 
> upgrade_cheapest
>     raise SomethingBeingBuiltError()
> village.SomethingBeingBuiltError: 'Unable to upgrade, check if something is 
> being built.'
>
> If I change line 253 to only "except:", everything works as
> expected. How come? What am I missing? Any help would be appreciated.
>
> P.S.: I'm aware I'm exposing my login/pass in the code. Don't care
> really, those are throwaway accounts.
>
> --
> "Now the storm has passed over me
> I'm left to drift on a dead calm sea
> And watch her forever through the cracks in the beams
> Nailed across the doorways of the bedrooms of my dreams"

http://www.travian.com/spielregeln.php -- rule 3???
-- 
http://mail.python.org/mailman/listinfo/python-list


daemonizing after binding to port

2010-06-18 Thread mk

Hello everyone,

I'm starting a SocketServer.TCPServer in my program, but since I want to 
report problems to script starting the program, I want to go daemon 
*after* TCPServer has done binding to port.


Is this likely to cause problems? I mean, my client works when I do the 
above, that is, it connects to the server. But I'm not sure if above is 
the Right Thing(tm).


First:

self.server = SocketServer.TCPServer((host, port), handleclass, 
bind_and_activate=False)

self.server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.server_bind()
self.server.server_activate()

(except etc skipped for brevity)

Second:

def daemonize(self):
try:
pid = os.fork()
except OSError, e:
print 'failed to fork:', str(e)
os._exit(1)
# if pid is non-zero, we're in parent
if pid:
os._exit(0)
os.setsid()
os.chdir(globalpath)
os.umask(0)




Regards,
mk

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


Re: catching my own exception

2010-06-18 Thread Steven D'Aprano
On Fri, 18 Jun 2010 17:08:45 +, nick wrote:

> I have a problem with catching my own exception. Here is the code:
> http://fly.srk.fer.hr/~nick/travapi/blame.php?repname=Travian+API&path=%
2Fvillage.py&
>
> Line 252 calls a method, which on line 207 raises a
> SomethingBeingBuiltError exception. On line 253 I catch that exception,
> but when I run that code, I get:
> 
> Traceback (most recent call last):
>   File "village.py", line 252, in 
> v.upgrade_cheapest()
>   File "/media/data/home/code/travapi/village.py", line 207, in
>   upgrade_cheapest
> raise SomethingBeingBuiltError()
> village.SomethingBeingBuiltError: 'Unable to upgrade, check if something
> is being built.'
> 
> If I change line 253 to only "except:", everything works as expected.
> How come? What am I missing? Any help would be appreciated.


I can't run your code, so I'm stuck with trying to guess how it works 
just by reading it. As far as I can tell, it should work. If it doesn't 
work, I can only imagine that you're not running the code you think you 
are running. Perhaps you're running an older version?


Other than that, I notice that your module throws away useful debugging 
information, and replaces it with bland, useless pap of no nutritional 
value:

try:
import account, fetch, resources, const
except Exception:
raise Exception('One or more travapi modules not available.')

Instead of a useful ImportError exception that tells the caller two 
important pieces of information (namely that it is an import error, and 
what the error actually was) you replace it with a useless, generic 
error. It might as well say "An error occurred" for all the use it is.

Errors should be *more* specific, not less. By replacing useful, specific 
exceptions with the generic Exception class, you're throwing information 
away and making your own job harder. Why would you rather see:

Exception: One or more travapi modules not available.

instead of this?

ImportError: No module named resources

As a general rule, anytime you find yourself writing:

except SomeSpecificException:
raise SomeOtherException

you should stop and think *really hard* about why you are bothering.



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


Re: super() woes (n00b)

2010-06-18 Thread Ethan Furman

Deadly Dirk wrote:

On Thu, 17 Jun 2010 12:18:33 -0700, Ethan Furman wrote:


Deadly Dirk wrote:

On Thu, 17 Jun 2010 13:48:45 -0400, J. Cliff Dyer wrote:


super gives you an instantiated version of the super class, which
means that you don't have to explicitly send self to any methods you
call on it.

So use `super().__init__()` instead.

Thanks. Interestingly enough, it works in Python 3, which is what the
book is about. It doesn't work in Python 2.6

as Thomas Jollans said days ago:
 > but you should really install Python 3.1 (it's in ubuntu, as others
 > have said!) because you will almost certainly hit into other snags.

or, as Gabriele Lanaro said in that same thread:
 > else take a book that covers python 2.x syntax

Cut-and-pasting-ly yours,

~Ethan~


As you can see, I followed the advice and installed the latest Python.



So you did.  My apologies.

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


Re: catching my own exception

2010-06-18 Thread nick
Dana Fri, 18 Jun 2010 10:36:21 -0700 (PDT), 
Jon Clements  kaze:
> http://www.travian.com/spielregeln.php -- rule 3???

Yeah, I know. If it's any consolation to you, I'm not doing it for the
fun of wining the game (hence not bothering to hide de code) but for
the fun of coding the API. :-)

Anyway, catching your own exceptions?

-- 
"Now the storm has passed over me
I'm left to drift on a dead calm sea
And watch her forever through the cracks in the beams
Nailed across the doorways of the bedrooms of my dreams"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: catching my own exception

2010-06-18 Thread Peter Otten
nick wrote:

> I have a problem with catching my own exception. Here is the code:
> 
http://fly.srk.fer.hr/~nick/travapi/blame.php?repname=Travian+API&path=%2Fvillage.py&;
> 
> Line 252 calls a method, which on line 207 raises a
> SomethingBeingBuiltError exception. On line 253 I catch that
> exception, but when I run that code, I get:
> 
> Traceback (most recent call last):
>   File "village.py", line 252, in 
> v.upgrade_cheapest()
>   File "/media/data/home/code/travapi/village.py", line 207, in
>   upgrade_cheapest
> raise SomethingBeingBuiltError()
> village.SomethingBeingBuiltError: 'Unable to upgrade, check if something
> is being built.'
> 
> If I change line 253 to only "except:", everything works as
> expected. How come? What am I missing? Any help would be appreciated.
> 
> P.S.: I'm aware I'm exposing my login/pass in the code. Don't care
> really, those are throwaway accounts.

You are importing your main script elswhere. Your code then 
effectively becomes

try:
# in another module
raise village.SomethingBuiltError 
except __main__.SomethingBeingBuiltError:
   print "caught"

i. e. you get two versions of every class that are built from the same code 
but not (recognized as) identical.

Solution: move your startup code into a separate file and have it import the 
village module.

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


Re: Possible to reach back in stack and grab calling function's locals()?

2010-06-18 Thread python
Ryan,

Thank you very much - your example is exactly the technique I was
looking for.

My use case is unusual and we don't need to update the parent's version
of locals().

The code in question is an internal template library whose methods need
access to their caller's locals() so they can figure out how to expand
variable references in string expressions. Eventually this library will
be replaced with a more conventional template package; however, for the
moment, I'm just keeping what we currently have working smoothly :)

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


Re: Jewish Pirates of the Mediteranean

2010-06-18 Thread small Pox
Excellen VIDEO !!! Verrry Rare !!!

http://watch.ctv.ca/news/latest/air-india-report/#clip314854


On Jun 17, 8:41 pm, small Pox  wrote:
> Excellent Video, VERRRY RARE !!!
>
> http://www.youtube.com/watch?v=r-72jGkGbsg
>
> On Jun 16, 2:25 am, nanothermite911fbibustards
>
>  wrote:
> > Jewish Pirates of the 
> > Caribbeanhttp://www.youtube.com/watch?v=cFSjKaiN47I&feature=related
>
> > Python
> > Jewish Pirates of the Caribbean
> > Lisp
> > (Jewish-Pirates  Caribbean)
>
> > I rcvd appreciative and supporting replies from many of you. The world
> > is moving in the direction of the Biblical predictions. I agree to
> > some extent that we should encourage the jews to accelerate their self-
> > destruction by applauding their crimes.
>
> >http://jewwatch.com/
>
>

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


Re: how to convert a sudsobject into its representative XML?

2010-06-18 Thread Phlip
The answer is to use ZSI instead, then call:

sw = SoapWriter()
sw.serialize(msg)
-- 
http://mail.python.org/mailman/listinfo/python-list


Generator (re-)definition within a loop

2010-06-18 Thread Pierre Reinbold
Hi all,

This is my first post on the list. I'm mainly a sysadmin and no expert
in programming languages, so this may be a stupid question but it
puzzles me.

I was pondering on the documentation of the function product(*args,
**kwds) in the itertools module. It is said that:

This function is equivalent to the following code, except that the
actual implementation does not build up intermediate results in memory:

def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)

Ok, then what about using a generator expression instead of a list
comprehension to avoid generating the intermediate results in memory?

Letting the **kwds trick aside, it may give:

def genexp_product(*args):
pools = map(tuple, args)
result = [[]]
for pool in pools:
result = (x+[y] for x in result for y in pool)
for prod in result:
yield tuple(prod)

but this do not work as expected:

>>> print list(product("ABC", "xy"))
[('A', 'x'), ('A', 'y'), ('B', 'x'), ('B', 'y'), ('C', 'x'), ('C', 'y')]
>>> print list(genexp_product("ABC", "xy"))
[('x', 'x'), ('x', 'y'), ('y', 'x'), ('y', 'y')]

My question is why ? What is the final generator "result" at the end of
the main loop in genexp_product ? How is it build exactly ? Is this an
effet of some sort of "lazy evaluation" ?

Thanks for your help in understanding this,


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


Re: Help with suds: HTTP Error 401

2010-06-18 Thread plainsane
On Jun 11, 8:27 am, Eric von Horst  wrote:
> Hi,
>
> I am trying to do a very simple thing with SUDS but I think I am
> missing the obvious (first time I use suds)
>
> I have small program that tries to open a wsdl. When I execute the
> program I am getting 'suds.transport.TransportError: HTTP Error 401:
> Unauthorized' Seems obvious but I specify username and pwd in the
> code.
> when use IE to go the wsdl, I get a pop-up asking me for the username
> and pwd, I enter them, and the wsdl is displayed.
>
> This is my code:
> "
> from suds import WebFault
> from suds.client import Client
> from suds.transport.http import HttpAuthenticated
>
> t = HttpAuthenticated(username='admin', password='admin')
>
> client = Client('http://.xxx.xx.x:8080/axis2/services/UcmdbService?
> wsdl', transport=t)
> "
> I seems straightforward :(
>
> Any help much appreciated.
>
> Erik

im having the same issue as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


I run into a problem in opening a file in Python

2010-06-18 Thread Justin Park
The problem is simple.
I have 50taxa2HGT_1.txt in the current directory,
and I can open it using any text editor (which indicates there actually
is.)

And I can read it in Python using
>>> fd=open("./50taxa2HGT_1.txt", "r")
, and it actually got opened, because I can do
>>> for line in fd:
... print line

But when I change the file access mode into "a",
it returns an error message of "IOError: [Errno 9] Bad file descriptor. "

What have I done wrong?

Thanks in advance,



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


Re: GUIs - A Modest Proposal

2010-06-18 Thread Jeff Hobbs
On Jun 10, 1:13 am, "Martin v. Loewis"  wrote:
> > That said, PerlTk didn't use Tcl did it?
>
> If you are referring tohttp://search.cpan.org/~srezic/Tk-804.028/-
> this also has a full Tcl interpreter, in pTk/mTk, and uses Tcl_Interp
> and Tcl_Obj throughout. From the Perl/Tk FAQ (*):
>
> "However, from a Perl perspective, Perl/Tk does not require any
> familiarity with Tcl, nor does its installation depend on any Tcl code
> apart from that packaged within Perl/Tk."
>
> They also explain
>
> "The pTk code proper is an externally callable Tk toolkit (i.e. a
> re-write of the Tk 8.0 code that allows easier external linking &
> calling, especially by perl)."
>
> I couldn't quite understand what they mean by that: the sources for
> tcl/generic (for example) look fairly unmodified.

Perl/Tk, as referenced above, does indeed replace the Tcl interpreter
with a bolt-on replacement using Perl internals.  While this was
workable, it was brittle and harder to maintain.

Tkx (http://search.cpan.org/dist/Tkx/), a replacement Tk binding for
Perl, authored by myself (core Tcl member, with knowledge of Perl
internals as well) and others at ActiveState, reintroduced the Tcl
binding in a very flexible way.  It's actually the Tcl module (http://
search.cpan.org/dist/Tcl/) that has all the magic.  Tk is loaded
dynamically from that - Perl has no direct linkage to it.

Tkx proved to be faster, more flexible and more extensible than the
original Perl/Tk.  The interface also took advantage of Tcl's stubs
mechanism to provide a level of binary version independence (Perl's
Tcl module can load any Tcl 8.4, 8.5 or 8.6 patchlevel without
recompilation, with 100% functionality).

If you look to revamp things, don't go down the path of trying to
remove Tcl to get to Tk.  Instead reconsider the approach to Tcl.  A
little bending might prove a much better match in the long term.

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


Re: I run into a problem in opening a file in Python

2010-06-18 Thread Ian Kelly
On Fri, Jun 18, 2010 at 2:26 PM, Justin Park  wrote:
> But when I change the file access mode into "a",
> it returns an error message of "IOError: [Errno 9] Bad file descriptor. "
>
> What have I done wrong?

"a" is for appending only.  You can't read from a file opened in that
mode.  If you want to both read and append, you should use mode 'r+'
or 'a+', depending on whether you want the stream initially positioned
at the beginning or end of the file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GUIs - A Modest Proposal

2010-06-18 Thread Jeff Hobbs
On Jun 6, 2:11 pm, rantingrick  wrote:
> On Jun 6, 2:06 pm, Mark Lawrence  wrote:
> > On 06/06/2010 16:31, rantingrick wrote:
>
> > > On Jun 5, 9:22 pm, ant  wrote:
>
> > >> I ask the group; should we try to create a new GUI for Python, with
> > >> the following
> > >> properties?:
>
> > >> - Pythonic
> > >> - The default GUI (so it replaces Tkinter)
> > >> - It has the support of the majority of the Python community
> > >> - Simple and obvious to use for simple things
> > >> - Comprehensive, for complicated things
> > >> - Cross-platform
> > >> - Looks good (to be defined)
> > >> - As small as possible in its default form
>
> > > Yes i one hundred percent agree! The only problem is i am the only
> > > one! Good luck finding others to climb into this boat. From the
> > > beginning there has has been this really weird love-hate relationship
> > > with Tkinter in the Python community. I myself experience this
> > > emotional attachment every day as i wish for Tkinter to be more
> > > "pretty" and "feature-rich" whilst at the same time loving it's
> > > simplicity. Tkinter seems to be Python's whipping boy and nobody wants
> > > to whip another, so we are stuck in limbo with a lobotomy.
>
> > > Heres an idea though, why not expand Tkinter with some new really cool
> > > widgets...? Hmmm...? That TIX package is a real PITA and could use a
> > > re-write. Can you believe it took until py3.0 for Tkinter to get a
> > > combobox :-O! Yea i know! :'-(
>
> > Patches are welcome at any time.  I look forward to seeing your first
> > contribution.
>
> > Kindest regards.
>
> > Mark Lawrence.
>
> Hello Mark,
>
> Are you maintaining Tkinter or Tix or both? There is a nagging issue
> with Tix that needs fixing. Upon subbclassing some widgets and when
> using the import Tix and import Tix as *. Maybe it is already fixed in
> 3.0 (i have not checked) but we need to fix it.
>
> I am still currently rewriting Tkinter Tix and IDLE in my spare time
> but got a bit busy lately. Anyhoo, i would really like to bring some
> patches, upgrades, and just a general spit shining to the entire three-
> plexx so let me know.

I am not a Tkinter maintainer, but I am one of the core Tk and Tix
maintainers (having also completely revamped Tix a couple of years ago
for better long-term stability and compatibility).  If you have fixes
that are relevant there, I can integrate them.  I should note that
much of Tix has been subsumed or replaced by better equivalents in the
core of Tk.  That said, it assumes you know and are using Tk 8.5.
I've seen a lot of FUD on Tk in this thread, and much of it is a
decade old perspective.  Tk 8.5 does have native themed widgets (using
Win32, Carbon or Cocoa, and X11, though also with plugins to gtk and
qt).  I'd have to explore more into Tkinter to see where anybody
derives value from Tix in current programs.

In any case, the basic mantra for Tix is new development should avoid
it, but existing development should work fine.  New development should
leverage the good work of Guilherme Polo in making the Tk 8.5 core
themed widgets available in Tkinter.

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


Re: I run into a problem in opening a file in Python

2010-06-18 Thread MRAB

Justin Park wrote:

The problem is simple.
I have 50taxa2HGT_1.txt in the current directory,
and I can open it using any text editor (which indicates there actually
is.)

And I can read it in Python using

fd=open("./50taxa2HGT_1.txt", "r")

, and it actually got opened, because I can do

for line in fd:

... print line

But when I change the file access mode into "a",
it returns an error message of "IOError: [Errno 9] Bad file descriptor. "

What have I done wrong?

Thanks in advance,


Mode "a" opens the file for appending, which means that you can't read
from it, only write to it.

For Python 2.6.5 on Windows XP Pro I get:

IOError: File not open for reading

which is more helpful.

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


Re: I run into a problem in opening a file in Python

2010-06-18 Thread D'Arcy J.M. Cain
On Fri, 18 Jun 2010 15:26:14 -0500
Justin Park  wrote:
> But when I change the file access mode into "a",
> it returns an error message of "IOError: [Errno 9] Bad file descriptor. "

Exact test script and traceback please.  I would like to see what line
gives you the error.  Are you trying to read the file that you opened
in append mode?

By the way, your email address doesn't work.  I get a "relay access
denied" message.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I run into a problem in opening a file in Python

2010-06-18 Thread D'Arcy J.M. Cain
On Fri, 18 Jun 2010 17:22:00 -0400
"D'Arcy J.M. Cain"  wrote:
> By the way, your email address doesn't work.  I get a "relay access
> denied" message.

Ignore that.  It was a local problem that I fixed before sending but
forgot to remove this paragraph.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generator (re-)definition within a loop

2010-06-18 Thread Terry Reedy

On 6/18/2010 3:57 PM, Pierre Reinbold wrote:

Hi all,

This is my first post on the list. I'm mainly a sysadmin and no expert
in programming languages, so this may be a stupid question


no


but it puzzles me.

I was pondering on the documentation of the function product(*args,
**kwds) in the itertools module. It is said that:

This function is equivalent to the following code, except that the
actual implementation does not build up intermediate results in memory:


I suspect the actual algorithm is an iterative algorithm that simulates 
nested for-loops to produce one item at a time, much like the working 
nested generator version I give below.


def product(*args, **kwds):
 # product('ABCD', 'xy') -->  Ax Ay Bx By Cx Cy Dx Dy
 # product(range(2), repeat=3) -->  000 001 010 011 100 101 110 111
 pools = map(tuple, args) * kwds.get('repeat', 1)
 result = [[]]
 for pool in pools:
 result = [x+[y] for x in result for y in pool]


This runs iter(result) to completion *before* rebinding the result to 
'result'.



 for prod in result:
 yield tuple(prod)

Ok, then what about using a generator expression instead of a list
comprehension to avoid generating the intermediate results in memory?

Letting the **kwds trick aside, it may give:

def genexp_product(*args):
 pools = map(tuple, args)
 result = [[]]
 for pool in pools:
 result = (x+[y] for x in result for y in pool)


The name binding in the first for-clause in a genexp is handled slightly 
differently from that in subsequent for-clauses. I suspect that this is 
relevant here. This code rebinds 'result' to a new generator *without* 
running running the previously bound 'result' generator.



 for prod in result:
 yield tuple(prod)


This runs N nested generators, but which?


but this do not work as expected:


print list(product("ABC", "xy"))

[('A', 'x'), ('A', 'y'), ('B', 'x'), ('B', 'y'), ('C', 'x'), ('C', 'y')]

print list(genexp_product("ABC", "xy"))

[('x', 'x'), ('x', 'y'), ('y', 'x'), ('y', 'y')]

My question is why ? What is the final generator "result" at the end of
the main loop in genexp_product ? How is it build exactly ? Is this an
effet of some sort of "lazy evaluation" ?


That and/or a namespace issue.

Let's apply Reedy's Rule: when you have trouble understanding a function 
expression, replace it with the (near) equivalent def statement. (Among 
other advantages, one can insert print calls!)


Genexps, like lambdas, are specialized function expressions.

def augment(s_of_s, s):
 for x in s_of_s:
  for y in s:
   yield x+[y]

def gen_product(*args):
pools = map(tuple, args)
result = [[]]
for pool in pools:
result = augment(result,pool)
for prod in result:
yield tuple(prod)

print(list(gen_product("ABC", "xy")))

>>> #3.1
[('A', 'x'), ('A', 'y'), ('B', 'x'), ('B', 'y'), ('C', 'x'), ('C', 'y')]

Terry Jan Reedy

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


Re: GUIs - A Modest Proposal

2010-06-18 Thread Ethan Furman

Jeff Hobbs wrote:

On Jun 6, 2:11 pm, rantingrick  wrote:

On Jun 6, 2:06 pm, Mark Lawrence  wrote:

On 06/06/2010 16:31, rantingrick wrote:

On Jun 5, 9:22 pm, ant  wrote:

I ask the group; should we try to create a new GUI for Python, with
the following
properties?:
- Pythonic
- The default GUI (so it replaces Tkinter)
- It has the support of the majority of the Python community
- Simple and obvious to use for simple things
- Comprehensive, for complicated things
- Cross-platform
- Looks good (to be defined)
- As small as possible in its default form

Yes i one hundred percent agree! The only problem is i am the only
one! Good luck finding others to climb into this boat. From the
beginning there has has been this really weird love-hate relationship
with Tkinter in the Python community. I myself experience this
emotional attachment every day as i wish for Tkinter to be more
"pretty" and "feature-rich" whilst at the same time loving it's
simplicity. Tkinter seems to be Python's whipping boy and nobody wants
to whip another, so we are stuck in limbo with a lobotomy.
Heres an idea though, why not expand Tkinter with some new really cool
widgets...? Hmmm...? That TIX package is a real PITA and could use a
re-write. Can you believe it took until py3.0 for Tkinter to get a
combobox :-O! Yea i know! :'-(

Patches are welcome at any time.  I look forward to seeing your first
contribution.
Kindest regards.
Mark Lawrence.

Hello Mark,

Are you maintaining Tkinter or Tix or both? There is a nagging issue
with Tix that needs fixing. Upon subbclassing some widgets and when
using the import Tix and import Tix as *. Maybe it is already fixed in
3.0 (i have not checked) but we need to fix it.

I am still currently rewriting Tkinter Tix and IDLE in my spare time
but got a bit busy lately. Anyhoo, i would really like to bring some
patches, upgrades, and just a general spit shining to the entire three-
plexx so let me know.


I am not a Tkinter maintainer, but I am one of the core Tk and Tix
maintainers (having also completely revamped Tix a couple of years ago
for better long-term stability and compatibility).  If you have fixes
that are relevant there, I can integrate them.  I should note that
much of Tix has been subsumed or replaced by better equivalents in the
core of Tk.  That said, it assumes you know and are using Tk 8.5.
I've seen a lot of FUD on Tk in this thread, and much of it is a
decade old perspective.  Tk 8.5 does have native themed widgets (using
Win32, Carbon or Cocoa, and X11, though also with plugins to gtk and
qt).  I'd have to explore more into Tkinter to see where anybody
derives value from Tix in current programs.

In any case, the basic mantra for Tix is new development should avoid
it, but existing development should work fine.  New development should
leverage the good work of Guilherme Polo in making the Tk 8.5 core
themed widgets available in Tkinter.

Jeff


Thanks for the info, Jeff!

Is there a good web-site / tutorial / book / etc that you would 
recommend for getting a good handle on Tk 8.5?


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


Re: max time threads

2010-06-18 Thread pacopyc
On 18 Giu, 01:04, MRAB  wrote:
> pacopyc wrote:
> > Hi, I'm trying to work with threads and I need your help. This is
> > code:
>
> > from threading import Thread
> > from Queue import Queue
> > import time
> > import random
>
> > def test_fun (k,q,t):
> >     time.sleep(t)
> >     print "hello world from thread " + str(q.get()) + " (sleep time =
> > " + str(t) + " sec.)"
> >     q.task_done()
>
> > queue = Queue()
> > for i in range (1,10):
> >     queue.put(i)
> > for j in range(queue.qsize()):
> >     num = random.randint(1,30)
> >     worker = Thread(target=test_fun, args=(j,queue,num))
> >     worker.setDaemon(True)
> >     worker.start()
> > queue.join()
>
> > Execution:
>
> > hello world from thread 1 (sleep time = 5 sec.)
> > hello world from thread 2 (sleep time = 5 sec.)
> > hello world from thread 3 (sleep time = 6 sec.)
> > hello world from thread 4 (sleep time = 8 sec.)
> > hello world from thread 5 (sleep time = 10 sec.)
> > hello world from thread 6 (sleep time = 13 sec.)
> > hello world from thread 7 (sleep time = 18 sec.)
> > hello world from thread 8 (sleep time = 19 sec.)
> > hello world from thread 9 (sleep time = 20 sec.)
>
> > Some questions for you:
>
> > 1) Why order is always the same (thread 1, thread 2, thread 3 
> > thread 9) and also seconds are always increasing? I don't understand.
> > 2) I'd like to decide a max time for each thread. If max time = 7 sec.
> > I want to print only threads with sleep time <= 7 sec. How can I do?
> > Can you modify my code?
>
> > Thank you very much
>
> 1)
>
> First it puts the numbers 1..9 into 'queue', then it starts 9 threads,
> giving each a number 'num'.
>
> Each thread waits for 'num' seconds ('t' in the thread).
>
> The thread with the lowest value of 'num' wakes first, gets the first
> entry from 'queue' (the value 1), and therefore prints "thread 1".
>
> The thread with the second-lowest value of 'num' wakes next, gets the
> second entry from 'queue' (the value 2), and therefore prints "thread
> 2".
>
> And so on.
>
> 2)
>
> If a thread is given a value of 'num' of more than a maximum, that
> thread shouldn't print its output, but it should still get the entry
> from the queue (assuming that you want it to still behave the same
> otherwise).

Ok, the problem is that I want fix a time max for each thread. For
example run 10 threads (each can terminate its work in 10 sec. max
fixed time) and wait them. If they finish its work in < 10 sec. (for
example 2 sec.) very good ... go on immediately (don't wait
unnecessary time), but if a thread use more than 10 sec. stop wait (I
kill it)  when all threads have finished their work or when they
have used all their available time (10 sec.) the program must go on
(don't wait).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I run into a problem in opening a file in Python

2010-06-18 Thread Terry Reedy

On 6/18/2010 4:26 PM, Justin Park wrote:

The problem is simple.
I have 50taxa2HGT_1.txt in the current directory,
and I can open it using any text editor (which indicates there actually
is.)

And I can read it in Python using

fd=open("./50taxa2HGT_1.txt", "r")

, and it actually got opened, because I can do

for line in fd:

... print line

But when I change the file access mode into "a",
it returns an error message of "IOError: [Errno 9] Bad file descriptor. "

What have I done wrong?


You did not copy and paste the *complete* error message, which would say 
whether the error occurred when opening or reading the file.


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


Re: GUIs - A Modest Proposal

2010-06-18 Thread Jeff Hobbs
On Jun 18, 2:59 pm, Ethan Furman  wrote:
> Jeff Hobbs wrote:
> > On Jun 6, 2:11 pm, rantingrick  wrote:
> >> On Jun 6, 2:06 pm, Mark Lawrence  wrote:
> >>> On 06/06/2010 16:31, rantingrick wrote:
>  On Jun 5, 9:22 pm, ant  wrote:
> > I ask the group; should we try to create a new GUI for Python, with
> > the following
> > properties?:
> > - Pythonic
> > - The default GUI (so it replaces Tkinter)
> > - It has the support of the majority of the Python community
> > - Simple and obvious to use for simple things
> > - Comprehensive, for complicated things
> > - Cross-platform
> > - Looks good (to be defined)
> > - As small as possible in its default form
>  Yes i one hundred percent agree! The only problem is i am the only
>  one! Good luck finding others to climb into this boat. From the
>  beginning there has has been this really weird love-hate relationship
>  with Tkinter in the Python community. I myself experience this
>  emotional attachment every day as i wish for Tkinter to be more
>  "pretty" and "feature-rich" whilst at the same time loving it's
>  simplicity. Tkinter seems to be Python's whipping boy and nobody wants
>  to whip another, so we are stuck in limbo with a lobotomy.
>  Heres an idea though, why not expand Tkinter with some new really cool
>  widgets...? Hmmm...? That TIX package is a real PITA and could use a
>  re-write. Can you believe it took until py3.0 for Tkinter to get a
>  combobox :-O! Yea i know! :'-(
> >>> Patches are welcome at any time.  I look forward to seeing your first
> >>> contribution.
> >>> Kindest regards.
> >>> Mark Lawrence.
> >> Hello Mark,
>
> >> Are you maintaining Tkinter or Tix or both? There is a nagging issue
> >> with Tix that needs fixing. Upon subbclassing some widgets and when
> >> using the import Tix and import Tix as *. Maybe it is already fixed in
> >> 3.0 (i have not checked) but we need to fix it.
>
> >> I am still currently rewriting Tkinter Tix and IDLE in my spare time
> >> but got a bit busy lately. Anyhoo, i would really like to bring some
> >> patches, upgrades, and just a general spit shining to the entire three-
> >> plexx so let me know.
>
> > I am not a Tkinter maintainer, but I am one of the core Tk and Tix
> > maintainers (having also completely revamped Tix a couple of years ago
> > for better long-term stability and compatibility).  If you have fixes
> > that are relevant there, I can integrate them.  I should note that
> > much of Tix has been subsumed or replaced by better equivalents in the
> > core of Tk.  That said, it assumes you know and are using Tk 8.5.
> > I've seen a lot of FUD on Tk in this thread, and much of it is a
> > decade old perspective.  Tk 8.5 does have native themed widgets (using
> > Win32, Carbon or Cocoa, and X11, though also with plugins to gtk and
> > qt).  I'd have to explore more into Tkinter to see where anybody
> > derives value from Tix in current programs.
>
> > In any case, the basic mantra for Tix is new development should avoid
> > it, but existing development should work fine.  New development should
> > leverage the good work of Guilherme Polo in making the Tk 8.5 core
> > themed widgets available in Tkinter.
>
> > Jeff
>
> Thanks for the info, Jeff!
>
> Is there a good web-site / tutorial / book / etc that you would
> recommend for getting a good handle on Tk 8.5?

Most of the Tk 8.5 references will be Tcl-based, but one that is cross-
language is Mark Roseman's www.tkdocs.com.

For books, there is John Ousterhout's main book, now in the 2nd
edition, updated with Tcl/Tk 8.5 references:
  http://www.amazon.com/Tcl-Toolkit-2nd-John-Ousterhout/dp/032133633X

To understand just the changes in Tk 8.5, you can see the wiki page
that lists references for all changes:
  http://wiki.tcl.tk/10630

It includes 16 new widgets (many themed versions of classic widgets,
but key new ones like the combobox and notebook), new canvas and text
features, and more.  The wiki in general has lots of how-to reference
info (over 20K pages of content).

The key with Tk that I've seen misunderstood in this thread is that it
has lots of extensions.  Those in the core community do argue about
whether "important" widgets should be full core or kept as widgets
(where they get their own dev cycle).  There are some fantastic Tk
widgets out there, like tktreectrl (http://
tktreectrl.sourceforge.net/), tktable, many in tklib (e.g. tablelist
http://www.nemethi.de/tablelist/tablelist.html), and more.  They can
be used with any of the languages that integrate with Tk, but may not
have "built-in" support (IOW, you might need some language-specific
shim).  Overcoming these hurdles may help reduce the pain and glum
feelings people have towards Tk bound to non-Tcl languages (and is
indeed one of the points addressed by Tkx).  It doesn't help with doc
translation (for use with other languages), so that's yet another
hurdle.  :-/

Jeff
-- 
htt

Re: max time threads

2010-06-18 Thread MRAB

pacopyc wrote:



[snip]

Ok, the problem is that I want fix a time max for each thread. For
example run 10 threads (each can terminate its work in 10 sec. max
fixed time) and wait them. If they finish its work in < 10 sec. (for
example 2 sec.) very good ... go on immediately (don't wait
unnecessary time), but if a thread use more than 10 sec. stop wait (I
kill it)  when all threads have finished their work or when they
have used all their available time (10 sec.) the program must go on
(don't wait).


It's not possible to kill a thread. If you want a thread to have a
maximum time, the thread must check occasionally how long it has been
running and terminate if necessary.

Another programming language (Java) originally had the ability to kill
threads, but that was later deprecated because it caused problems due to
not knowing what the thread was doing when it was killed (it might have
been in the middle of updating something at the time, for example,
leaving the system in an inconsistent state).
--
http://mail.python.org/mailman/listinfo/python-list


Re: constructing an object from another instance of the same class

2010-06-18 Thread Christoph Groth
Bruno Desthuilliers  writes:

> Anyway: the simplest solution here is to replace the call to your Base
> class with a call to a factory function. I'd probably go for something
> like (Q&D untested code and other usual warnings) :
>
> (...)

Yeah, that will do what I want.

My confusion arose from the expectation that there had to be some
mechanism to do the conversion automatically.  But actually a simple

def bar(arg):
if not isinstance(arg, Base):
arg = Base(arg)
# Do something with arg.

is a simple and explicit solution of the problem.

Thanks
Christoph

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


Re: max time threads

2010-06-18 Thread pacopyc
On 19 Giu, 00:27, MRAB  wrote:
> pacopyc wrote:
>
> [snip]
> > Ok, the problem is that I want fix a time max for each thread. For
> > example run 10 threads (each can terminate its work in 10 sec. max
> > fixed time) and wait them. If they finish its work in < 10 sec. (for
> > example 2 sec.) very good ... go on immediately (don't wait
> > unnecessary time), but if a thread use more than 10 sec. stop wait (I
> > kill it)  when all threads have finished their work or when they
> > have used all their available time (10 sec.) the program must go on
> > (don't wait).
>
> It's not possible to kill a thread. If you want a thread to have a
> maximum time, the thread must check occasionally how long it has been
> running and terminate if necessary.
>
> Another programming language (Java) originally had the ability to kill
> threads, but that was later deprecated because it caused problems due to
> not knowing what the thread was doing when it was killed (it might have
> been in the middle of updating something at the time, for example,
> leaving the system in an inconsistent state).

Ok, I understand. But is possible fix max wait time (for example 60
sec.) in main thread and check queue for task done and at the same
time the remaining time. When all task have done or wait time has
expired main thread go on. Is it possible? Can you write code?
Thank you very much.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: constructing an object from another instance of the same class

2010-06-18 Thread Christoph Groth
Steven D'Aprano  writes:

> On Fri, 18 Jun 2010 16:30:00 +0200, Christoph Groth wrote:
>
>> If other is of type Base already, just "pass it on".  Otherwise,
>> construct an instance of Base from it.
>> 
>>  import
>> numpy as np
>> 
>> class Base:
>> def __init__(self, other):
>> if isinstance(other, type(self)):
>> self = other
>> return
>
> This does not do what you think it does. I wonder whether you've
> actually tried it?

Just quickly.  Sorry, I should have written

class Base:
def __init__(self, other):
if isinstance(other, type(self)):
self.a = other.a
self.b = other.b
self.c = other.c
self.d = other.d
return
# ...

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


Re: max time threads

2010-06-18 Thread MRAB

pacopyc wrote:

On 19 Giu, 00:27, MRAB  wrote:

pacopyc wrote:

[snip]

Ok, the problem is that I want fix a time max for each thread. For
example run 10 threads (each can terminate its work in 10 sec. max
fixed time) and wait them. If they finish its work in < 10 sec. (for
example 2 sec.) very good ... go on immediately (don't wait
unnecessary time), but if a thread use more than 10 sec. stop wait (I
kill it)  when all threads have finished their work or when they
have used all their available time (10 sec.) the program must go on
(don't wait).

It's not possible to kill a thread. If you want a thread to have a
maximum time, the thread must check occasionally how long it has been
running and terminate if necessary.

Another programming language (Java) originally had the ability to kill
threads, but that was later deprecated because it caused problems due to
not knowing what the thread was doing when it was killed (it might have
been in the middle of updating something at the time, for example,
leaving the system in an inconsistent state).


Ok, I understand. But is possible fix max wait time (for example 60
sec.) in main thread and check queue for task done and at the same
time the remaining time. When all task have done or wait time has
expired main thread go on. Is it possible? Can you write code?
Thank you very much.


The documentation says that queue.join() can't have a timeout, so you
might have to think of another way to achieve the same effect.

You could, for example, have a results queue into which a thread puts
something to indicate when it has finished, and then use the .get method
on it in the main thread (the .get method can have a timeout).
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I fix this test so it runs on Windows? (it uses tzset)

2010-06-18 Thread Nobody
On Thu, 17 Jun 2010 11:45:03 +0100, Chris Withers wrote:

>> For whatever reason, tython's "time" module doesn't provide the tzset()
>> function on Windows. However, you should be able to use it via ctypes.
> 
> This sounds pretty heavyweight for a unit test.
> I'm not even sure how I would do this ;-)

from ctypes import cdll
tzset = cdll.msvcrt._tzset

Except ... Python doesn't appear to use the OS time conversion functions,
so calling _tzset() has no effect.

And the documentation doesn't specify whether modifying time.timezone is
allowed.

IOW, I don't think there's any robust way to ask "what would have happened
if TZ been set to  at startup", other than running a separate
script with the appropriate TZ setting.

You can perform conversions with an explicit timezone using the "datetime"
module, but that won't help you test the behaviour of code which uses the
"time" module.

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


Re: Communicating with a program using subprocess

2010-06-18 Thread Nobody
On Thu, 17 Jun 2010 11:22:37 +0200, Laurent Verweijen wrote:

> This is easy to understand, but I want to pipe it's input/output
> by another python program. (I will show what I am doing on the
> console to test it)
> 
> >>> from subprocess import *
> >>> p = Popen(["python", "increment.py"], stdin=PIPE, stdout=PIPE)
> >>> p.communicate("5")
> Traceback (most recent call last):
>   File "increment.py", line 4, in 
> n = int(raw_input(n)) + 1
> EOFError: EOF when reading a line

> The problem is that I want to use communicate multiple times
> before closing the file.
> 
> How could I achieve this

Don't use communicate(). Use p.stdin.write() to send input, use
p.stdin.close() then p.wait() when you're finished.

If you also want to read the child process' stdout, either:

1. ensure that the child *never* writes more than a buffer's worth of data
at a time (the exact value is implementation-dependent, but up to 4K
should be fine for any modern Unix; I don't know about Windows),

2. use a separate thread for reading stdout,

3. use non-blocking I/O (use the fcntl module for Unix, you need PyWin32
for Windows), or

4. have the process write to a file instead of a pipe.

See the implementation of subprocess.Popen.communicate for clues.

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


Re: GUIs - A Modest Proposal

2010-06-18 Thread Kevin Walzer

On 6/18/10 6:16 PM, Jeff Hobbs wrote:



Is there a good web-site / tutorial / book / etc that you would
recommend for getting a good handle on Tk 8.5?


Most of the Tk 8.5 references will be Tcl-based, but one that is cross-
language is Mark Roseman's www.tkdocs.com.

For books, there is John Ousterhout's main book, now in the 2nd
edition, updated with Tcl/Tk 8.5 references:
   http://www.amazon.com/Tcl-Toolkit-2nd-John-Ousterhout/dp/032133633X

To understand just the changes in Tk 8.5, you can see the wiki page
that lists references for all changes:
   http://wiki.tcl.tk/10630

It includes 16 new widgets (many themed versions of classic widgets,
but key new ones like the combobox and notebook), new canvas and text
features, and more.  The wiki in general has lots of how-to reference
info (over 20K pages of content).

The key with Tk that I've seen misunderstood in this thread is that it
has lots of extensions.  Those in the core community do argue about
whether "important" widgets should be full core or kept as widgets
(where they get their own dev cycle).  There are some fantastic Tk
widgets out there, like tktreectrl (http://
tktreectrl.sourceforge.net/), tktable, many in tklib (e.g. tablelist
http://www.nemethi.de/tablelist/tablelist.html), and more.  They can
be used with any of the languages that integrate with Tk, but may not
have "built-in" support (IOW, you might need some language-specific
shim).  Overcoming these hurdles may help reduce the pain and glum
feelings people have towards Tk bound to non-Tcl languages (and is
indeed one of the points addressed by Tkx).  It doesn't help with doc
translation (for use with other languages), so that's yet another
hurdle.  :-/

Jeff


To see the new ttk widgets at work in Tkinter, look at the next 
generation of the venerable app PySol, PySolFC, at 
http://pysolfc.sourceforge.net. Here are screenshots of (I think) the 
Windows versions:


http://pysolfc.sourceforge.net/screenshots.html

And the Mac version:

http://mac.softpedia.com/progScreenshots/PySolFC-Screenshot-24708.html

Here's a screenshot from one of my own Tkinter applications that makes 
use of ttk widgets and also such Tk extension packages as BWidgets (the 
treeview) and tablelist (the table view):


http://www.codebykevin.com/phynchronicity-running.png

--Kevin


--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
--
http://mail.python.org/mailman/listinfo/python-list


500 tracker orphans; we need more reviewers

2010-06-18 Thread Terry Reedy

Go to the bottom of
http://bugs.python.org/iss...@template=search&status=1
enter 1 in the Message Count box and hit Search.

At the moment, this gets 510 hits. Some have had headers updated, nearly 
half have had a person add himself as 'nosy' (put 1 in the Nosy count 
box to count those that have not), but none have a written response.


In the past two weeks, I have commented on some old orphans and gotten a 
couple of previously orphaned patches applied and the issue closed. But 
I am not prepared to spend my whole life on this ;=).


We need more issue reviewers.
Clearly.
If you want to contibute, opportunity is here.
With 500 orphans, and 2200 other open issues,
there must be something that matches your interests and abilities.
Use other search fields to narrow the choices.

If you want to contibute to the tracker, this may help:
http://wiki.python.org/moin/TrackerDocs/
Then read examples of comments already there.

Or consider my first-response comment to
http://bugs.python.org/issue8990

To write that, I

* verified the reported behavior, though I forgot to explicitly say so; 
when doing so, include version and system (such as 3.1.2, WinXP), as 
that is sometimes helpful.


* read the relevant doc section and pasted it in to establish a basis 
for discussion (the OP might have done that, but did not, so I did).


Everyone reading this should at least be able to do this much for an 
issue like this, and this much *is* helpful.


* compared behavior and doc and concluded that there is a bug.

* read the posted patch as best I could, which is not much in this case, 
but it at least looked like a real diff file.


* noticed that the diff did *not* patch the appropriate unit test file.

* discussed two possible fixes and identified which the OP choose.

* wrote an 'executive summary' both for the OP and future reviewers.

Oh yes, I also adjusted the headers. Although new reviewers cannot do 
that, you *can* suggest in the message what changes to make.


Special offer to readers of this thread, especially new reviewers:
if you make such a suggestion, you may email me, subject: Tracker, with 
one clickable link like the above, cut and pasted from the browser URL 
box, per line of the message.


Perhaps you are shy and uncomfortable saying much. Well so was I. I 
started about 5 years ago with *safe* comments and have s l o w l y 
expanded my comfort zone. The shock of discovering this week that there 
are 500 orphans, some 2 years old, expanded it. After no response for a 
year or two, even an imperfect response must be better than nothing.


While there is occasional negativity on the tracker, I believe it 
averages less per message than python-list, which itself is pretty decent.


Terry Jan Reedy

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


subprocess in Command promt+ webbrowser

2010-06-18 Thread shanti bhushan
I have a code ,in which i invoke the local webserver in back
ground ,then open URL and access the web page.
below is my code.
I am able to invoke and kill the local webserver in seperate python
script,but when i club opening of browser and and subprocess , my like
below ,then my script is not responding.
Please guide me.

import subprocess
import time
subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /C "D:\372\pythonweb
\mongoose-2.8.exe -root D:\New1\ >YourOutput.txt"')
webbrowser.open("http://43.88.79.229:8080/index.html/";)
time.sleep(11)
subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /c "taskkill /F /IM
mongoose-2.8.exe >YourOutput1.txt"') # kill in back ground
time.sleep(3)
subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /C "D:\372\pythonweb
\mongoose-2.8.exe -root D:\New1\ >YourOutput.txt"')
webbrowser.open("http://43.88.79.229:8080/index.html/";)
time.sleep(11)
subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /c "taskkill /F /IM
mongoose-2.8.exe >YourOutput1.txt"') # kill in back ground
time.sleep(3)
subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /C "D:\372\pythonweb
\mongoose-2.8.exe -root D:\New2\ >YourOutput.txt"')
webbrowser.open("http://43.88.79.229:8080/index.html/";)




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


Re: GUIs - A Modest Proposal

2010-06-18 Thread est
>
> Having said all that, I would like to eliminate some of the
> depedencie. At some point I'll probably re-do the Windows
> implementation using ctypes, because pywin32/mfc is hindering
> more than helping in some areas. I'm also thinking about ways
> to interface directly with Cocoa without going through pyobjc.
> But all that is some way off in the future after I get the API
> nailed down more.
>
> --
> Greg


that would be awesome!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GUIs - A Modest Proposal

2010-06-18 Thread Matt

On 06/17/2010 08:50 AM, Grant Edwards wrote:

On 2010-06-16, Matt  wrote:

On 06/05/2010 09:22 PM, ant wrote:


 PyQt is tied to one platform.


Several posters have asked for support for or clarification of this 
claim of yours.


Let me guess...

The one platform it's tied to is Qt?



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


Re: subprocess in Command promt+ webbrowser

2010-06-18 Thread shanti bhushan
On Jun 19, 11:01 am, shanti bhushan  wrote:
> I have a code ,in which i invoke the local webserver in back
> ground ,then open URL and access the web page.
> below is my code.
> I am able to invoke and kill the local webserver in seperate python
> script,but when i club opening of browser and and subprocess , my like
> below ,then my script is not responding.
> Please guide me.
>
> import subprocess
> import time
> subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /C 
> "D:\372\pythonweb\mongoose-2.8.exe >YourOutput.txt"')
time.sleep(3)
webbrowser.open("http://43.88.79.229:8080/index.html";)
time.sleep(11)
subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /c "taskkill /F /IM
mongoose-2.8.exe >YourOutput1.txt"') # kill in back ground
time.sleep(3)
subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /C "D:\372\pythonweb
\mongoose-2.8.exe -root D:\New1\ >YourOutput.txt"')
time.sleep(3)
webbrowser.open("http://43.88.79.229:8080/index.html";)
time.sleep(11)
subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /c "taskkill /F /IM
mongoose-2.8.exe >YourOutput1.txt"') # kill in back ground
time.sleep(3)
subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /C "D:\372\pythonweb
\mongoose-2.8.exe -root D:\New2\ >YourOutput.txt"')
time.sleep(3)
webbrowser.open("http://43.88.79.229:8080/index.html";)
time.sleep(11)
subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /c "taskkill /F /IM
mongoose-2.8.exe >YourOutput1.txt"') # kill in back ground


This scripts works fine with python 26 in windows XP, but when i
replace the browser opening part with broswer to be open on different
machine in python made tool.That it always give me warning that
process already open.If i kill the the command then also it gives same
problem.
Please guide me is it sycronisation issue?,some exception handling is
required??
-- 
http://mail.python.org/mailman/listinfo/python-list