What is the slickest way to transpose a square list of lists (tuple of tuples)?

2006-01-08 Thread Gerard Brunick
My way is ugly.  These has to be a better way.

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


Can you fix up wrapper function argument signatures?

2006-11-27 Thread Gerard Brunick
Consider:

 >>> def negate(func):
... def wrapper(*args, **kwargs):
... return not func(*args, **kwargs)
... return wrapper
...
 >>> def f(x):
... return x > 10
...
 >>> g = negate(f)
 >>> g(20)
False
 >>> g(5)
True

Now g has the argument signature of (*args, **kwargs).  Pop-up help in 
Python
Scripter(which is great by the way) tells me this, as does

 >>> g.func_code.co_varnames
('args', 'kwargs')

Is there anyway to fix this in negate?  I assume that I can't just start
changing things in g.func_code since the bytecodes depend on the order
of variables and lots of other stuff that I don't claim to understand.

Please note: From the new functools module, I see that one can set/update
__module__, __name__, __doc__, and __dict__ using the corresponding 
attributes
from the wrapped function; however, none these fix up the argument signature
do they?  (I'm still running 2.4, so I haven't tried it.)

Thanks,
Gerard

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


Where does a class closure live?

2006-12-06 Thread Gerard Brunick
Consider:

###  Function closure example

def outer(s):
... def inner():
... print s
... return inner
...
 >>> f = outer(5)
 >>> f()
5
 >>> dir(f)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', 
'__get__', '__getattribute__', '__hash__', '__init__', '__module__', 
'__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 
'func_dict', 'func_doc', 'func_globals', 'func_name']

###  Class instance closure example

 >>> def outer2(s):
... class Inner(object):
... def __call__(self):
... print s
... return Inner()
...
 >>> f = outer2(10)
 >>> f()
10
 >>> dir(f)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', 
'__getattribute__', '__hash__', '__init__', '__module__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 
'__weakref__']

# Class closure example

 >>> def outer3(s):
... class Inner(object):
... def __call__(self):
... print s
... return Inner
...
 >>> F = outer3(15)
 >>> f = F()
 >>> f()
15
 >>> dir(F)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', 
'__getattribute__', '__hash__', '__init__', '__module__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 
'__weakref__']


Now the closure for the function live in func_name.   I've even done the 
exercise where I build a dummy  inner function that returns its closed 
variable, so that I can use that thing to reach through "cells" and 
check out the variables living in the closure object.  Where are the 
closure variables for the class instance, and the class?  Can I get my 
hands on them in Python?
-Gerard
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with closures

2006-12-07 Thread Gerard Brunick
I can't solve your problem, but I can at least explain why I think its 
hard.  foo doesn't have any closed over
variables.  Some of its locals have to live in cells, so that pre and 
post can see them in their closures.

 >>> foo.func_code.co_cellvars
('x', 'y')

Now the only way that I know of to get a local variable to be put in a 
cell, where you can then plug
it into a func_closure, it to write a function which a contains a 
function with a closure.  Moreover, this
requires that the function signatures really match to work.  Consider

 >>> def test(*arg, **args):
... def inner():
... print x
... return inner
...
 >>> f = test(x=5)
 >>> f()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in inner
NameError: global name 'x' is not defined

Since x isn't a named argument of test, the compiler just assumes that 
its a global.
This means that your contract function is going to have to build a 
string and exec
to make the newf so its arguments match foo exactly.  Of course the 
compiler is
really finicky about exec, when there are free variables around, and I 
don't claim
to understand the rules.



alain wrote:
> Hi,
>
> I have a problem with closures.
> I am trying to implement yet another design by contract decorator which
> would look like the following:
> 
> def contract(f):
>   def newf(*args, **kw):
>   import new
>   precondition =  new.function(f.func_code.co_consts[1],
>   f.func_globals,'pre',
>   f.func_defaults,
>   f.func_closure)
>   precondition()
>   result=f(*args, **kw)
>   postcondition=new.function(f.func_code.co_consts[2],globals())
>   postcondition(result)
>   return result
>   return newf
> @contract
> def foo(x,y,g=2,z=1):
>   def pre():
>   assert x>1 and 0   def post(result):
>   assert result >0
>   print 'main'
>   return x+y+z*g
>
> print foo(2,5,4,69)
> 
>
> The problem is that i get the following error message on line 7:
> TypeError: arg 5 (closure) must be tuple
>
> f.func_closure is indeed empty while
> f.func_code.co_consts[1].co_freevars is logically equal to ('x','y').
>
> Thanks for responding
>
> Alain
>

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


Adding functions to classes after definition

2007-01-08 Thread Gerard Brunick
Consider:  A)
 >>> class C(object):
... pass
...
 >>> def f(*args):
... print args
...
 >>> C.f = f
 >>> C.f

 >>> c=C()
 >>> c.f()
(<__main__.C object at 0x04A51170>,)

And B)

 >>> del c
 >>> C.f = types.MethodType(f, None, C)
 >>> C.f

 >>> c = C()
 >>> c.f()
(<__main__.C object at 0x04A51290>,)

I don't understand A).  It is my vague understanding, that methods are
really properties that handle binding on attribute access, so B) should
be the "right" way to add a method to a class after definition.  Why does
A show up as a method?  Shouldn't it still just be a function?  Certainly
when you define a class, there is some magic in the __new__ method that
turns functions in the initial dictionary into methods, but does this still
happen for all setattr after that?  Is is possible to set a class attribute
equal to a regular (types.FunctionType) function?

Any references that discuss these issues would be greatly appreciated.

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


Can you escape a % in string that will used for substitution

2007-10-18 Thread Gerard Brunick
Is there a way to do:

s = "I like python %i%s of the time."
print s % (99, "%")

without having to pass in "%"?

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


Short confusing example with unicode, print, and __str__

2008-03-05 Thread Gerard Brunick
I really don't understand the following behavior:

 >>> class C(object):
... def __init__(self, s): self.s = s
... def __str__(self): return self.s
...
 >>> cafe = unicode("Caf\xe9", "Latin-1")
 >>> c = C(cafe)
 >>> print "Print using c.s:", c.s
Print using c.s: Café
 >>> print "Print using just c:", c
Print using just c: Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
position 3: ordinal not in range(128)
 >>> str(c)
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
position 3: ordinal not in range(128)

Why would "print c.s" work but the other two cases throw an exception?
Any help understanding this would be greatly appreciated.

Thanks in advance,
Gerard
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Short confusing example with unicode, print, and __str__

2008-03-05 Thread Gerard Brunick
Gary Herron wrote:
> Gerard Brunick wrote:
>> I really don't understand the following behavior:
>>
>>  >>> class C(object):
>> ... def __init__(self, s): self.s = s
>> ... def __str__(self): return self.s
>> ...
>>  >>> cafe = unicode("Caf\xe9", "Latin-1")
>>  >>> c = C(cafe)
>>  >>> print "Print using c.s:", c.s
>> Print using c.s: Café
>>  >>> print "Print using just c:", c
>> Print using just c: Traceback (most recent call last):
>>   File "", line 1, in 
>> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
>> position 3: ordinal not in range(128)
>>  >>> str(c)
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
>> position 3: ordinal not in range(128)
>>
>> Why would "print c.s" work but the other two cases throw an exception?
>> Any help understanding this would be greatly appreciated.
>>
>> Thanks in advance,
>> Gerard
>>   
> It's the difference between how __str__ and __repr__  act on strings.
>
> Here's s simpler example
>
> >>> d=unicode("Caf\xe9", "Latin-1")
> >>> repr(d)
> "u'Caf\\xe9'"
> >>> str(d)
> Traceback (most recent call last):
>  File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
> position 3: ordinal not in range(128)
>
> Gary Herron
It seems the question is more about what does print do.  Lets extend 
your example:

 >>> d=unicode("Caf\xe9", "Latin-1")
 >>> repr(d)
"u'Caf\\xe9'"
 >>> print d
Café
 >>> str(d)
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
position 3: ordinal not in range(128)

Why doesn't the print statement that a UnicodeEncodeError?  I assumed 
that print calls str and then prints
the result, but this doesn't seem to be the case.  What the heck does 
print do?
-- 
http://mail.python.org/mailman/listinfo/python-list