[Python-ideas] Fwd: Define a method or function attributeoutsideof a class with the dot operator
markusmeskanen at gmail.com
Sun Feb 12 12:55:57 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.
Aren't they the same though? Remember that classes are instances of type
and methods are just their attributes. We're simply using setattr() in both
cases: with instances, and with classes (=instances).
> 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.
I think you missed the point, the decorator was just an example and has
arbitary functionality. The point is that you can not refer the class
itself in its body, so you can't do either of these methods:
def concenate(self, other: Foo) -> Foo:
def map(self) -> dict:
Because Foo is not defined at the time of executing the function headers.
The proposed feature would allow you to easily define these after the class
definition and allow refering to the class directly.
my_menu = Menu(['Pizza', 'Cake', 'Pasta'])
> def my_menu.select_callback(item_index):
> if item_index == 0: # Pizza
> else: # Cake or Pasta
Attaching to the instance is fine too. But I prefer the current spelling
my_menu1 = Menu(['Pizza', 'Cake', 'Pasta'])
my_menu2 = Menu(...)
def callback1(self, ...):
def callback2(self, ...):
my_menu1.callback = callback2
my_menu2.callback = callback1
I don't, it is repeating the variable name three times. I don't see how
this differs from decorator syntax, do you prefer the old way on that too,
or am I missing something?
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
I think you answered yourself here, this would not remove the existing
flexible way. Just like @decorator syntax didn't remove the more flexible
way. Honestly this is in my opinion almost one-to-one comparable with
decorator syntax, and I don't think anyone here dares to claim decorators
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas