How can I definine a class inside a function, then access it from outside said function in Python?

Viewed 54

Let's assume I have the following code:

#!/usr/bin/python3
def genclass():
  class stuff:
    foo = 'Foo'
    bar = 'Bar'

genclass()

How would I access that class outside of the function? I tried the following:

  • Just print the function:

print(stuff.foo)

  • Print it with the function name:

print(genclass.stuff.foo)

  • Same, but with () to indicate that genclass is a function:

print(genclass().stuff.foo)

Unfortunately, none of the above worked.

2 Answers

One way is you can store the class objects in a list and return the list, but you can only access the classes by index.

def genclass():
    class stuff:
        foo = 'foo'
        bar = 'bar'
    class other:
        one = 'one'
        two = 'two'
    return [stuff, other]

>>> genclass()[0].foo
'foo'
>>> genclass()[1].one
'one'

But this is basically treating the function as a list.
edit::
You can also use it as both a function that executes another command if you include an if-statement to check if a parameter is passed.

def genclass(arg = None):
    class stuff:
        foo = 'foo'
        bar = 'bar'
    if arg:
        print('parameter passed')
    else:
        return [stuff]

>>> genclass()[0].bar
'bar'
>>> genclass(1)
parameter passed

What you want to do is setting an attribute in a function. You can't do it directly, but you need to call the setattr function.

You can do something like:

def genclass():
    class stuff:
        foo = 'Foo'
        bar = 'Bar'
    setattr(genclass, 'stuff', stuff)

And then, after executing the function, because everything inside a function is ran just after its execution, you can access the class by typing

genclass.stuff

Anyway, this is a workaround and I don't think it is a best practice.

For better understand what a function is in Python and why you can set them an attribute please have a look on https://www.tutorialspoint.com/What-are-Python-function-attributes

Related