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

David Mertz mertz at gnosis.cx
Sun Feb 12 12:30:18 EST 2017

I think the proposal, so far, seems to confuse two separate things.  One is
attaching a method to a class after definition.  The second is attaching a
method to an instance after creation.  Or at least it is unclear to me
which of those is the intention, since both seem to occur in the examples.
Or maybe it's both, but those feel like fairly different use cases.

Which is to say, we really need a PEP.  As it stands, I'm somewhere around
-0.75 on the idea.

>   def MyClass.method(self, other: MyClass) -> List[MyClass]:

In this case, the syntax is 100% superfluous.  One can simply write:

  def method(self, other: MyClass) -> List[MyClass]:

The class is already mentioned in the decorator.  If the intention is to
add the method to the class, that's fine, and something a decorator can
do.  Perhaps the spelling for this decorator-factory could be `enhance`.
Or more verbosely `inject_method`.  Spelling aside, the syntax adds nothing.

  my_menu = Menu(['Pizza', 'Cake', 'Pasta'])
>   def my_menu.select_callback(item_index):
>       if item_index == 0:  # Pizza
>           serve_food(pizza)
>       else:  # Cake or Pasta
>           ...

Attaching to the instance is fine too.  But I prefer the current spelling
so far:

my_menu1 = Menu(['Pizza', 'Cake', 'Pasta'])

my_menu2 = Menu(...)

def callback1(self, ...):
def callback2(self, ...):

my_menu1.callback = callback2

my_menu2.callback = callback1

Under the current approach, you can flexibly define callbacks outside of
the scope of any particular instance or class, and attach them as needed to
instances.  Obviously the new syntax would not *remove* this option, but it
would cover only a narrow subset of what we can already do... and the way
we do it now feels much better self-documenting as to intent.

Yours, David...

Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170212/306e7936/attachment.html>

More information about the Python-ideas mailing list