2

I'm surprised that the namespace of function parameters in a method is the class and not the global scope.

def a(x):
    print("Global A from {}".format(x))

class Test:
    def a(self, f=a):
        print("A")
        f("a")  # this will call the global method a()

    def b(self, f=a):
        print("B")
        f("b")   # this will call the class method a()

t=Test()
t.b()

How to explain that? And how would I access the global a() from the parameters of b?

1 Answer 1

2

Namespace lookups always check the local scope first. In a method definition, that is the class.

At the time of the definition of Test.a, there is no local named a, only the global a. By the time Test.b is defined, Test.a has already been defined, so the local name a exists, and the global scope is not checked.

If you want to point f in Test.b to the global a, use:

def a(x):
    print("Global A from {}".format(x))

class Test:

    def a(self, f=a):
        print("A")
        f("a")  # this will call the global method a()

    def b(self, f=None):
        f = f or a
        print("B")
        f("b")   # this will call the class method a()

t=Test()
t.b()

which prints

B
Global A from b

as expected.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That works. Yet, it's still new to me that the parameter namespace is different from the namespace in the method code...
Yeah, it was unexpected for me, too, until I got used to it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.