Python:如何执行生成的代码?

时间:2010-05-19 17:57:54

标签: django python

我有这段代码,我想使用app参数生成代码而不是重复代码。

if app == 'map':
    try:
        from modulo.map.views import map
        return map(request, *args, **kwargs)
    except ImportError:
        pass

elif app == 'schedule':
    try:
        from modulo.schedule.views import schedule
        return schedule(request, *args, **kwargs)
    except ImportError:
        pass

elif app == 'sponsors':
    try:
        from modulo.sponsors.views import sponsors
        return sponsors(request, *args, **kwargs)
    except ImportError:
        pass

elif app == 'streaming':
    try:
        from modulo.streaming.views import streaming
        return streaming(request, *args, **kwargs)
    except ImportError:
        pass

你有什么想法吗?

由于

2 个答案:

答案 0 :(得分:6)

我更喜欢使用dispatch-dictionary idiom,编码类似......:

import sys

dispatch = { 'map': ('modulo.map.views', 'map'),
             'schedule': ('modulo.schedule.views', 'schedule_day'),
             ...etc etc.. }
if app in dispatch:
  modname, funname = dispatch[app]
  try: __import__(modname)
  except ImportError: pass
  else:
    f = getattr(sys.modules[modname], funname, None)
    if f is not None:
      return f(request, *args, **kwargs)

不确定您认为“代码生成”会让您更喜欢这种方法。

答案 1 :(得分:0)

为什么不把这个功能传递给特定的功能?

def proc_app(request, app, *args, **kwargs):
    return app(request, *args, **kwargs):

def view_1(request):
    from modulo.map.views import map
    return proc_app(request, map, *args, **kwargs)

def view_2(request):
    from modulo.schedule.views import schedule_day
    return proc_app(request, schedule_day, *args, **kwargs)