3

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?

2
  • 2
    Please post your code as code so it's easily copiable. Commented Jun 16, 2017 at 11:13
  • @deceze, Ok, will do so in future. Commented Jun 16, 2017 at 12:04

2 Answers 2

5
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.

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

1 Comment

+1 for the detailed explanation and of course for this line Python class construction executes as code
2

When you are inside doSomethingWithEnum function, you are in the different namespace. To access anything that is defined in your class, like EnumClass, you should call self.EnumClass. If it were a class method, it would be cls.EnumClass.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.