better lambda support in the future?

Fredrik Lundh fredrik at pythonware.com
Fri Dec 17 16:33:34 EST 2004


Steven Bethard wrote:

> You're welcome to name the function whatever you want -- notice in my example that the function is 
> used in the statement:
>
> x = func or f
>
> If you'd prefer the statement to read:
>
> x = func or x
>
> that's also fine.  Depends on what exactly 'x' is, and whether or not it really makes sense for 
> the function I called 'f' to have the same name as the variable called 'x'.  It certainly may, but 
> since I wasn't giving real code, I didn't want to commit to that.

if you write "def f", "f" is a variable, just like "x".  "def" is an assignment
statement.

I'm not sure what "func" is supposed to be in your examples...

> I assume that the point you were trying to make is that:
>
> def f(*args):
>     return expr
>
> is equivalent to
>
> f = lambda *args: expr
>
> ?

>>> def f():
...     return 1+2
...
>>> g = lambda: 1 + 2
>>> type(f)
<type 'function'>
>>> type(g)
<type 'function'>

>>> import dis
>>> dis.dis(f)
  2           0 LOAD_CONST               1 (1)
              3 LOAD_CONST               2 (2)
              6 BINARY_ADD
              7 RETURN_VALUE
>>> dis.dis(g)
  1           0 LOAD_CONST               1 (1)
              3 LOAD_CONST               2 (2)
              6 BINARY_ADD
              7 RETURN_VALUE

>>> dir(f)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__ge
tattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__r
educe__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure',
 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_na
me']
>>> dir(g)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__ge
tattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__r
educe__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure',
 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_na
me']

>>> f.func_name
'f'
>>> g.func_name
'<lambda>'

</F> 






More information about the Python-list mailing list