2010-05-19 131 views
1

我有這段代碼,我想用app參數來生成代碼而不是重複它。Python:如何執行生成的代碼?

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 

你有什麼想法嗎?

感謝

+0

「生成」可能不是要走的路。使用一些內省更安全和簡單。 – Thomas 2010-05-19 18:01:32

回答

6

我寧願使用派遣詞典成語,編碼類似...:

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

在第二行代碼中,您在'地圖'後有一個逗號,而不是逗號) – systemovich 2010-05-20 13:53:40

+0

Tx,已編輯並修復。 – 2010-05-20 15:57:07

+0

使用'modname ='modulo。%s.views'%app'和'funname = app'它變成了我正在尋找的東西。謝謝 – Natim 2010-05-29 09:41:52

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)