There is a similar syntax for the php $$ variable in python

Is there a similar syntax for php $$ variable in python? that I am actually trying to load the model based on the value.

for example, if the value is Song, I would like to import the Song module. I know I can use if statements or lambada statements, but something like the php $$ variable would be very handy.

what i'm behind it looks like 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 the settings or can be obtained from the comandline. it can be any model in the project.

+2


source to share


4 answers


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

      



+3


source


I'm sure you want it __import__()

.

Read this: docs.python.org:__import__



This function is called by the import statement. It can be substituted (by importing a built-in module and assigning builtins.__import__

) to change the semantics of the import statement, but nowadays it is usually easier to use import hooks (see PEP 302

). Direct use __import__()

is rare, unless you want to import a module whose name is only known at runtime.

+1


source


It seems that you want to download all potentially compatible modules / models at hand, and as prompted, select the one you want. You can "globals ()", which returns a dictionary of global level variables, indexed by string. So if you do something like globals () ['Song'] it will give you the Song model. This is very similar to PHP $$, except that it will only capture the global scope variables. For local scope, you will need to call locals ().

Here's some sample 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 

      

+1


source


So, you know the general concept that you are trying to implement is called Reflective Programming.

You can see examples in multiple languages ​​in the wikipedia entry here

http://en.wikipedia.org/wiki/Reflective_programming

0


source







All Articles