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

Terry Reedy tjreedy at udel.edu
Thu Apr 23 16:23:19 EDT 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!")
> 
> 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!")
> 
> 
> 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.
> 
> 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!

There has been some discussion on py-dev and perhaps python-ideas, but I 
cannot remember any specifics as to why Guido was unpersuaded/negative.

If one regards

def name(params): body

as syntantic sugar for a (somewhat hypothetical) assignment statement

name = make_func('name', "params", "body")

(there is a function_maker function in the new module, though with a 
more complicated interface), then generalizing the target would seem 
reasonable.  The function's __name__ does not seem like an issue: 
"foo.bar" and "foo['bar']" both direct one to the proper definition code.

Counter-argument: class and import are also implied assignments, and 
they also subject to the same limitation.

Counter-counter-argument: a) doing actual assignments with name = 
type('name', bases, dict) and name = __import__('name',...) is more 
feasible, and b) the need for qualified names is less for class and 
probably for import and c) the restriction *could* also be lifted for 
those two statements also.

For some, a plus for this proposal is that is directly binds the 
function to the target without introducing a spurious name into the 
local scope.  It would thus reduce the perceived need for and hence 
pressure for generalized function expressions.  I believe Guido would 
consider this last point a plus if so stated.

I do not believe this recurring idea has been the subject of a PEP.  If 
not, writing one might be a service, should you choose to do so, even if 
rejected.

Terry Jan Reedy




More information about the Python-list mailing list