. Python 2.1 function attributes

Tim Peters tim.one at home.com
Sat Jan 27 18:01:27 EST 2001


[Robin Becker]
> mmmhhhh :( what happens with
>
> def f() >> x:
>         return 1
> ...
> def f() >> x:
>         y=2
>         return y

Raises InconsistentReturnError unless

    x is 1

evaluates true in the first example, or

    x is y

evaluates true in the second, at the time the "return" is executed.
Clearly, anything else would be error-prone!

> seems to me that having multiple ways of doing return is a bad idea

You might like this new 2.1 feature better then, best illustrated by
example:

>>> def f(\d+)(i):
...     return int(\1) + 1
...
>>> f12(6)
18
>>> f0(3)
3
>>> f666(42)
708
>>>

That is, "the name" of a function can be a regular expression now, and
anything that "looks like" a call is matched against all regexp func defs.
\1, \2 etc can  be used in the body of the function to return substrings of
the matched function name, just as for any other use of regexps in Python.

Of course there is a full set of disambiguating rules, based on the notion
of "most specific match".  For example,

def f.*(i):
    return i

also matches names like f12 and f666, but the set of strings matching f.* is
a strict superset of those matching f(\d+), so the latter is more specific.
By the same rule,

def f666(i):
    pass

is a more specific match than f(\d+), so f666 is unambiguous.

The primary reason for adding this was all the complaints about not being
able to reliably obtain the name of a function within its own body.  Now
it's available via \0.

>>> def anyfuncatall():
...     print \0
...
anyfuncatall
>>>

or, via the new attribute notation,

>>> anyfuncatall.\0
'anyfuncatall'
>>>

Combining this with the new return spelling is very powerful:

>>> x1 = 10
>>> x2 = 20
>>> x3 = 30
>>> def f(\d)() >> eval("x" + \1):
...     pass
...
>>> f2()
20
>>>

can't-wait-to-see-who-supports-this-one<wink>-ly y'rs  - tim





More information about the Python-list mailing list