I'm trying to understand how classes work a bit better "under the hood" of python.
If I create a class Foo like so
class Foo:
bar = True
Foo is then directly accessible, such as print(Foo) or print(Foo.bar)
However, if I dynamically create create a class and don't set it to a variable like so
type('Foo',(),{'bar':True})
If done in the interpreter it shows <class '__main__.Foo'>. However, when I try to print Foo it's undefined...NameError: name 'Foo' is not defined
Does this mean that when a class is created the "traditional" way (the first Foo class above), that python automatically sets a variable for the class of the same name? Sort of like this
# I realize this is not valid, just to convey the idea
Foo = class Foo:
bar = True
If so, then why doesn't python also create a variable named Foo set to class Foo when using type() to create it?
type()does not create a classtype('Foo',(),{'bar':True})result in<class '__main__.Foo'>?typecan and absolutely does create classes, though it it not its most common use case.Foo = type('Foo',(),{'bar':True}). With regards to why it doesn't create the class in your namespace.typeis just a function, and you wouldn't expect any other function to create new variable in your namespace, so why shouldtypebe special?