简体   繁体   中英

is there similar syntax to php's $$variable in python

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.

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()

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.

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 

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_programming

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM