Search code examples
pythonvariablesscopedefault-parametersdefault-arguments

Scope of variables in Python methods with identical default parameters?


After a good bit of searching i couldn’t find any examples covering this. But i might not be using the correct terminology, since im confused about the situation, and what to even ask if that makes sense? So i feel like this is a duplicate probably.

But if you have a Python class, with two methods that have a parameter that has the same name, whats the behaviour of this?

class Foo():

    def __init__(self, arg1=1, arg2=2):

    def methodOne(self, amount, setting=None, extra=0):         

    def methodTwo(self, amount, setting=None):
        ...
        #What is going on with setting here? What is setting referring to?
        self.methodOne(amount, setting=setting) 

Solution

  • The setting on the left can only be referring to a keyword argument, and the setting on the right can only be referring to a name. That's how Python's parser works.