Python metaprogramming

I am trying to archive a task that turns out to be a bit complicated since I am not very good at Python metaprogramming.

I want to have a locations module with a get_location(name) function that returns a class defined in folders / in a file with the name passed to the function. The class name is something like NameLocation.

So my folder structure:

 program.py locations/ __init__.py first.py second.py 

program.py will matter with:

 from locations import get_location location = get_location('first') 

and location is a class defined in first.py smth similar to this:

 from locations import Location # base class for all locations, defined in __init__ (?) class FirstLocation(Location): pass 

and etc.

Ok, I tried a lot of import and getattribute statements , but now I'm bored and give up. How to archive this behavior?


I don't know why, but this code

 def get_location(name): module = __import__(__name__ + '.' + name) #return getattr(module, titlecase(name) + 'Location') return module 

returns

 >>> locations.get_location( 'first') <module 'locations' from 'locations/__init__.py'> 

location module! why?

+4
source share
2 answers

You need an __import__ module; after that getting attr from it is not difficult.

 import sys def get_location(name): fullpath = 'locations.' + name package = __import__(fullpath) module = sys.modules[fullpath] return getattr(module, name.title() + 'Location') 

Edit : __import__ returns the package, so you will need another getattr , see the docs (and carefully read the entire section - "do as I say not like me", -).

+6
source

I think you are looking for:

 location = __import__('first') 
+1
source

Source: https://habr.com/ru/post/1304636/


All Articles