tags:

views:

201

answers:

4

is there similar syntax to php's $$variable in python? what I am actually trying is to load a model based on a value.

for example, if the value is Song, I would like to import Song module. I know I can use if statements or lambada, but something similar to php's $$variable will be much convenient.

what I am after is something similar to this.

from mypackage.models import [*variable]

then in the views

def xyz(request): 
    xz = [*variable].objects.all()

*variable is a value that is defined in a settings or can come from comandline. it can be any model in the project.

+3  A: 
def load_module_attr (path):
    modname, attr = path.rsplit ('.', 1)
    mod = __import__ (modname, {}, {}, [attr])
    return getattr (mod, attr)

def my_view (request):
    model_name = "myapp.models.Song" # Get from command line, user, wherever
    model = load_module_attr (model_name)
    print model.objects.all()
John Millikin
I am not sure if you understood my question. what I am trying to achieve is something similar to this.from mypackage.models import [*variable]then in the viewsdef xyz(request): xz = [*variable].objects.all()*variable is a value that is defined in setting or can come from comandline. it can be any model in the project. so your method does not really help with the problem.
Mohamed
I've updated the code -- is that closer to your problem?
John Millikin
I have not tested it yet, but syntactically looks like the solution.
Mohamed
A: 

So you know the general concept, what you are trying to implement is known as "Reflective Programming".

You can see examples in several languages in the wikipedia entry here

http://en.wikipedia.org/wiki/Reflective%5Fprogramming

michael
+1  A: 

I'm pretty sure you want __import__().

Read this: docs.python.org: __import__

This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but nowadays it is usually simpler to use import hooks (see PEP 302). Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime.

Jim Dennis
+1  A: 

It seems that you want to load all the potentially matchable modules/models on hand and according to request choose a particular one to use. You can "globals()" which returns dictionary of global level variables, indexable by string. So if you do something like globals()['Song'], it'd give you Song model. This is much like PHP's $$ except that it'll only grab variables of global scope. For local scope you'd have to call locals().

Here's some example code.

from models import Song, Lyrics, Composers, BlaBla

def xyz(request):
 try:
  modelname = get_model_name_somehow(request):
  model =globals()[modelname]
  model.objects.all()
 except KeyError:
  pass # Model/Module not loaded ... handle it the way you want to
sharjeel