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

Sven R. Kunze srkunze at mail.de
Wed Jun 1 15:04:29 EDT 2016


On 01.06.2016 17:29, Steven D'Aprano wrote:
> 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.

I consider a special syntax for this narrow kind of usecase way too much 
as it doesn't seem very flexible and extensible in the future.

Dunder methods/attributes/variables allow far more.

Especially while pondering over a reply to Michael's post, there's more 
to consider than just the name of the defining scope. One would need the 
scope itself. We could add another dunder attribute/method/variable for 
this as well; or provide a combined dunder access to it.

> 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

I admit it looks looks neat but to me it's not really worth such 
restricting syntax as explained above.

> 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.

I don't think so:

class Symbol:
     def __init__(self, name=None):
         self.name = name or __assigned_name__

>
>> 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__.

Sorry, if that was not clear. Here you are:

 >>> class X:
...     pass
...
 >>> X.__module__
'__main__'


So, we already have this kind of "let me know what my defining scope 
looked like" dunder attributes.


Best,
Sven


More information about the Python-ideas mailing list