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

Sven R. Kunze srkunze at mail.de
Wed Jun 1 11:10:47 EDT 2016


On 01.06.2016 16:06, Paul Moore wrote:
> I'm not sure I follow this proposal. Could you explain a little please?
>
> Given
>
>      x = Symbol('x')
>
> as the current approach, how would you modify that to work with your
> proposal? If you could show how you'd write a wrapper function
> AutoSymbol, so that
>
>      x = AutoSymbol()
>
> did the same as the above, that'd help me a lot.
>
> Thanks,
> Paul

Okay, let's see.


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 :)


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

A two-step approach like the following would also be possible:

class AutoSymbol:

     def __init__(self):
         pass # no name available :(

     def __name__(self, name):
         self.name = name  # that's me

In this case, name is not available in the constructor which could be 
regarded as a drawback. A advantage would be possible optimization. No 
__name__ member, no implicit call of __name__


On the caller site, nothing changes. It's just:


x = AutoSymbol()


Autosymbol either has __assigned_name__ set during constructor execution 
or __name__() will be set later. The same logic could be applied to 
other callables, functions, lambdas, etc.



This post does not really care about the name of the special 
variable/member. It could also be '__lhs__'. I think others will come up 
with better names. In the end, one name needs to be chosen of course. ;-)


Best,
Sven



More information about the Python-ideas mailing list