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
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)
returns
>>> locations.get_location( 'first') <module 'locations' from 'locations/__init__.py'>
location module! why?
source share