[Python-ideas] Quick idea: defining variables from functions that take the variable name

Steven D'Aprano steve at pearwood.info
Wed Jun 1 11:29:23 EDT 2016


On Wed, Jun 01, 2016 at 05:10:47PM +0200, Sven R. Kunze wrote:

> class Symbol:
>     def __init__(self, name):
>         self.name = name # that's me :)
> 
> 
> That's the current way. If now, the compiler would assign "x" to a 
> special dunder attribute/variable, that would allow __init__ to extract 
> that name and use it as if it were a parameter:
> 
> class AutoSymbol:
>     def __init__(self):
>         self.name = __assigned_name__ # that's me :)

I don't think that will work. Greg's proposal was to expand the syntax 
x -> Function(args) to

    x = Function(args)
    x.__name__ = 'x'

which means that the name won't be available until after __new__ and 
__init__ have completed.

If you want instead to use a magic local variable somehow injected 
automatically into the __init__ method at runtime, I think that's very 
clever. TOO clever, and far too magical. Automatically providing a 
function argument is quite easy to understand, since the argument is 
right there in the method definition, and it is conceptually just like 
"self". It also means that both of these will work will work exactly the 
same way:

x = Function('x', args)  # explicitly provide the name

x -> Function(args)  # use the new syntax


But with your magic __assigned_name__ local variable, the signature of 
the function must change depending on whether it is being called with 
one argument or two.


> That's just it. I consider __assigned_name__ the same as __module__. A 
> special variable available if you need it.

I'm not sure what you mean by __module__.

py> class A:
...     def __init__(self):
...             print(__module__)
...
py> a = A()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
NameError: name '__module__' is not defined




-- 
Steve


More information about the Python-ideas mailing list