1

getattr is fine when retrieving a method from an object and a string containing the method name (method of the object), like

getattr(object, 'method_name')

This is specified in more that a SO question, see for instance this one.

But what about a situation where you have a full string including the dotted path to the method, like

method_is = 'main_directory.directory.my_object.method_name'

Is there any way to call the method from the object my_object and use getattr (or eval). I cannot import my_object before calling the function.

The ugly hack would be of course splitting the string by the dot, but it won't even solve the issue anyway because you are left with strings, not objects for directories.

Community
  • 1
  • 1
mar tin
  • 9,266
  • 23
  • 72
  • 97
  • possible duplicate of [How to dynamically load a Python class](http://stackoverflow.com/questions/547829/how-to-dynamically-load-a-python-class) – UltraInstinct Feb 16 '15 at 16:53
  • @Thrustmaster Cheers for pointing out that duplicate, one of the answers solved my problem. – mar tin Feb 16 '15 at 17:04

1 Answers1

0

You're looking for import_string(dotted_path) that's defined here: https://github.com/django/django/blob/main/django/utils/module_loading.py

AqeelAT
  • 27
  • 7
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/33417112) – Simas Joneliunas Dec 18 '22 at 09:16