. Python 2.1 function attributes

Robin Becker robin at jessikat.fsnet.co.uk
Sat Jan 27 19:36:53 EST 2001


In article <mailman.980636553.17809.python-list at python.org>, Tim Peters
<tim.one at home.com> writes
...
Wow these are 'must have' features. I must start growing fingernails at
once.
>> 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
>
>

-- 
Robin Becker



More information about the Python-list mailing list