[Python-ideas] Fwd: Define a method or function attribute outside of a class with the dot operator

Chris Angelico rosuav at gmail.com
Fri Feb 10 06:05:30 EST 2017


On Fri, Feb 10, 2017 at 9:45 PM, Markus Meskanen
<markusmeskanen at gmail.com> wrote:
>> That saves one line, at the cost of introducing even more complexity to
>> the language.
>>
>> Are these use-cases common enough to justify the extra syntax?
>
>
> Keep in mind that the extra syntax is *very* minor, and goes hand-to-hand
> with the existing attribute access syntax. Basically it's taking the
> existing syntax to one more place, where it in my opinion should have been
> since long ago.
>

Every now and then, we get a proposal along these lines. I think it's
about time a PEP got written.

The usual way this is explained is that a function name can be
anything you can assign to. Currently, a function has to have a simple
name, and it then gets created with that as its __name__ and bound to
that name in the current namespace (module, class, or function). To
achieve what you're looking for, the syntax would be defined in terms
of assignment, same as a 'for' loop's iteration variable is:

# Perfectly legal
for spam.ham in iter: pass

# Not currently legal
def ham.spam(): pass

Markus, do you want to head this up? I'll help out with any editorial
work you have trouble with (as a PEP editor, I can assign it a number
and so on).

Considerations:

* What would the __name__ be? In "def ham.spam():", is the name "spam"
or "ham.spam"? Or say you have "def x[0]():" - is the name "x[0]" or
something else?
* Are there any syntactic ambiguities? Any special restrictions?
* Exactly what grammar token would be used? Currently NAME; might become 'test'?
* Will there be any possible backward incompatibilities?

Create a pull request against https://github.com/python/peps - looks
like the next number is 542.

Any questions, I'm happy to help.

ChrisA


More information about the Python-ideas mailing list