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

Steven D'Aprano steve at pearwood.info
Tue May 31 11:08:58 EDT 2016


On Tue, May 31, 2016 at 03:39:14PM +0100, Paul Moore wrote:

> [I still prefer "call the RHS with the name of the LHS as the
> argument" over "inject the name of the LHS as the first argument of
> the call present on the RHS", btw - 

Do I understand that you think that the RHS should be limited to 
callables that take a single argument only?

So far we have four real use-cases:

T = TypeVar('T')
x = sympy.Symbol('x')
cls = type('cls', bases, ns)
Record = nametuple('Record', fields)

You would only support the first two cases and leave the others with the 
status quo? That seems like a strange restriction to make. What problem 
do you think the other two use-cases would cause that the first two 
don't?

The fundamental use-case here is "any object that needs to know its own 
name". Most objects need more than just a name.

If you're worried that it will be confusing that we define a callable to 
take (say) three arguments:

class Widget:
    def __init__(self, name, foo, bar):
        ...

but then call it with only two:

spanner -> Widget(foo=1, bar=2)

I think you're worrying over nothing. In fact, I played a trick on 
you... I said we define a callable that takes three arguments, but in 
fact I defined it with FOUR. We're constantly writing methods that take 
an extra argument, self, that is provided by the compiler.

A similar argument applies to decorators:

# defined with a single argument
def decorator(func):
   ...

# called with no explicit argument (or even parens!)
@decorator


And both cases can be used without compiler magic, using an unbound 
method versus a bound method, decorator syntax versus calling the 
decorator by hand.

So while this is magic, it is the same sort of magic we deal with 
frequently in Python. So frequently that we forget just how magical it 
is that the "self" param is provided automatically for us.




-- 
Steve


More information about the Python-ideas mailing list