I'm trying to archive a task which turns out to be a bit complicated since I'm not very good at Python metaprogramming.
I want to have a module locations
with function get_location(name)
, which returns a class defined in a folder locations/ in the file with the name passed to function. Name of a class is something like NameLocation.
So, my folder structure:
program.py
locations/
__init__.py
first.py
second.py
program.py will be smth with with:
from locations import get_location
location = get_location('first')
and the location is a class defined in first.py smth like this:
from locations import Location # base class for all locations, defined in __init__ (?)
class FirstLocation(Location):
pass
etc.
Okay, I've tried a lot of import and getattribute statements but now I'm bored and surrender. How to archive such behaviour?
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'>
the locations module! why?!