Why can function definitions only use identifiers, and not attribute references or any other primaries?

Gary Herron gherron at islandtraining.com
Thu Apr 23 16:52:01 CEST 2009


Jeremy Banks wrote:
> Hi. I'm sure there've been debates about this before, but I can't seem
> to figure out what to search for to pull them up, so I'm asking here.
>
> It seems to me that a lot of things could be made much easier if you
> could use primaries other than basic identifiers for the target of
> function definitions. For example, if attribute references were
> allowed I'd be able to do:
>
>     def foo.bar():
>         return("I'm a method!")
>   

There's no need for a specific addition to the syntax to do this.

Try this:

    def foo_bar():
        return(...)
    foo.bar = foo_bar

> If we wanted to get even more liberal (which I don't see as a bad
> thing, but I could see being found more objectionable by some), we
> could allow the use of anything that's a valid assignment target. For
> example:
>
>     def foo["bar']():
>         return("I'm a function referenced in a mapping object!")
>   

and this:

    def foo_bar():
        return(...)
    foo["bar"] = foo_bar



>
> In this case I could see there being a problem in that there's nothing
> to get the function's __name__ from, but that doesn't apply for the
> first example.
>   

Not sure what you mean here.


> Many uses of this may not be Pythonic, but I'm sure there are many
> that are. It just feels like an arbitrary restriction, preventing
> users from doing something that may be useful.
>
> Any feedback or direction to previous discussion on the subject would
> be appreciated. Thanks!
> --
> http://mail.python.org/mailman/listinfo/python-list
>   




More information about the Python-list mailing list