1

I wrote below code snippet:

def definer():
    class A:
        print("Inside class")

definer()
a = A()

and got following output on command line

Inside class
Traceback (most recent call last):
  File "tuple.py", line 81, in <module>
    a = A()
NameError: name 'A' is not defined

Why is A not defined after running definer()?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
vir
  • 11
  • 2
  • Related reading: [Is it a bad idea to define a local class inside a function in python?](https://stackoverflow.com/q/22497985/2745495) – Gino Mempin Mar 04 '23 at 11:09

1 Answers1

2

Most of the time, what happens within a function, stays in that function. In this case, you define a class that belongs to the function local namespace and it ceases to be after the function exists. If you want to use it outside, you need to return it (alternatively, you can try making it a global variable):

def definer():
    class A:
        def hello(self):
            return 'hello'
    return A

A = definer()
a = A()
print(a.hello())
bereal
  • 32,519
  • 6
  • 58
  • 104