12

Suppose I have myfile.py with some classes A, B and C defined INSIDE it. Now I want to instantiate class by it's name in str. I don't understand what to pass to getattr in order to do this. All examples like this assume that classes are in other module:

module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()

but I don't have module_name.

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

29

If you are on the same module they are defined you can call globals(), and simply use the class name as key on the returned dictionary:

Ex. mymodule.py

class A: ...
class B: ...
class C: ...

def factory(classname):
    cls = globals()[classname]
    return cls()

Above solution will also work if you are importing class from another file

Otherwise, you can simply import the module itself inside your functions, and use getattr (the advantage of this is that you can refactor this factory function to any other module with no changes):

def factory(classname):
     from myproject import mymodule
     cls = getattr(mymodule, classname)
     return cls()
amol rane
  • 325
  • 1
  • 13
jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • I don't want to hardcode `myproject` and `mymodule`, it should be current file – Dims Jul 02 '18 at 19:17
  • 1
    So, it is also answered above - just use `globals()`. There is no downside, it is documented behavior and part of the language specifications. – jsbueno Jul 02 '18 at 19:22
  • Someone - (IIRC @coddy) ha just edited this answer with two extra lines suggesting another way of accomplishing the task. Said suggestion was,on my knowledge, _and_ uon trying it, plain incrrect. Pleas, if you have a new way to answer the question, do that in a new answer by your user. Edits for improving grammar and formatting are welcome. – jsbueno May 18 '20 at 12:44