Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner class usage python. Global name is not defined

Tags:

python

I have a question about inner classes usage in python. I know that this is a bad practice but anyway. I am wondering about scope where inner class is defined. I got an error 'global name 'ClassName' is not defined'. My code snippet looks like this: enter image description here

I discovered that to avoid getting this error I can use:

ClassWithEnum.EnumClass

instead of:

EnumClass

inside of doSomethingWithEnum() function. So I am wondering if there is any other way to make EnumClass defined inside of doSomethingWithEnum() function? And why there is no such error when I declare EnumClass as a default parameter in doSomethingWithEnum() function?

like image 369
Bill Avatar asked Sep 27 '26 23:09

Bill


1 Answers

class ClassWithEnum(object):
    class EnumClass(object):
        ...

    def doSomethingWithEnum(self, m = EnumClass....):
        ...

Python class construction executes as code. The def statement is really a line of code being executed that creates a function. The class keyword introduces a namespace. Putting these two mechanisms together, it means that class EnumClass really creates an object by that name in the current namespace, not much different from what foo = 'bar' does, so within the same namespace you can refer to it by that name, which is what happens in the def statement.

Also compare:

class Foo:
    bar = 'baz'
    print bar
    baz = bar

Every line of code inside a class block is a regular executable line of code.

Once your class definition is done, you're out of the ClassWithEnum namespace and cannot access EnumClass anymore simply by that name; it's now only available as ClassWithEnum.EnumClass; whether from "outside" the class or from within a function (any function, including class methods).

To get access to the class without typing its name from within the method you could do:

type(self).EnumClass

Or simply self.EnumClass, since properties are looked up up the chain.

like image 106
deceze Avatar answered Sep 29 '26 11:09

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!