mikatakana
mikatakana

Reputation: 523

How to call modules methods by name?

I have module with some logic handlers

 - handlers
   - __init__.py
   - items.py (with class Items)
   - users.py (with class Users)
 - app.py

In main script app.py I need to create instance of Items or Users class and call some action. Dynamically, by some params like { collection: "items", method: "get" }

oItems = items.Items()
oItems.get()

I know how to load all handlers from module: from handlers import *, but I don't know how to create instance of collection class and call method.

Without dynamic collection it would be

method = getattr(items.Items(), 'get')
method()

But create an instance - is a problem for me. I'm trying

 oItems = type('items.Items', (), {})

but it create instance for __main__ module, not handlers

Upvotes: 0

Views: 29

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124170

Modules are just objects with attributes, really. As such you can dynamically retrieve those attributes:

 collection_module = getattr(handlers, 'items')
 collection_class = getattr(collection_module, 'Items')
 collection = collection_class()

You could just store the in a dictionary for easier lookup:

 handlers_mapping = {'items': items.Items, 'users': users.Users}

and then use handlers_mapping[type_name]() or similar.

Upvotes: 1

Related Questions