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

Matthias welp boekewurm at gmail.com
Fri Feb 10 05:15:38 EST 2017


Hi Markus,

Thanks for writing this up, as I've had this same very valid problem before.

On 10 February 2017 at 10:13, Markus Meskanen <markusmeskanen at gmail.com> wrote:
> I'm suggesting the addition of support to using a dot notation when defining
> a function to be a method of a class, or a callback attribute.

Your solution to me seems like a 'hack': class monkey-patching during runtime
is already available if you really need it, and your proposal only
makes it easier,
which I don't really like.

> This functionality would be useful in the few rare cases where the class
> itself needs to be accessed in the function's definition (decorator, typing,
> etc

This problem could just as well be solved by allowing access to a scope-level
variable (__class__? __type__?) which is available in the class body at
construction time, which points to the (eventual) class type object,
or evaluating
the type hints in a class only after the class is created, which then
allows for that
class to be pointed to in the type annotations.

E.G. this does not work right now:

    class A:
        def foo(self: A):
            pass

as it fails with NameError: A is not defined, whereas you'd expect it to work.

The problem is very annoying when you're trying to work with the dunder
methods for e.g. numerical objects, as you cannot say '+ is only allowed for
these types', but it is not limited to this scope only.


-Matthias


More information about the Python-ideas mailing list