On Tue, May 05, 2020 at 04:05:20AM -0000, Brandt Bucher wrote:
> > We should have a mechanism that collects the current function or method's 
> > parameters into a dict, similar to the way locals() returns all local 
> > variables.
> 
> Maybe I'm missing something here, but how about... `locals`? It works exactly 
> as you hope:

Using locals() is fragile. Consider:

    # Works fine.
    def method(self, args, spam, eggs, cheese):
        var(self).update(locals())
        for x in args:
            print(x)


    # Suprise! This is broken!
    def method(self, args, spam, eggs, cheese):
        for x in args:
            print(x)
        var(self).update(locals())

(For brevity, I have ignored the "filter out self" issue.)

One might not even notice that you have exposed the local x. Most people 
write unit tests to check for the presence of expected attributes; I 
don't know anyone who writes unit tests for the *absense* of unexpected 
attributes.

The problem with locals() is that as soon as you move the call to locals 
out of the very first executable statement in the method, you risk 
contaminating it with unwanted local variables that aren't parameters.

The most insidious problem will be cases that *nearly always* work:

    if very_rare_condition:
        x = something
        ...
    vars(self).update(**locals())



> It's a fairly common idiom to just collect `locals()` on the first 
> line of a function or method with lots of arguments

Indeed, but it's that requirement that it must be precisely on the first 
executable statement of the function that makes it fragile.


-- 
Steven
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/LG72WHK3GAKM6HZ3LGSLFXAGZRPWMPTG/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to