views:

118

answers:

2

Hello guys

I have this code, and I would like to use the app parameter to generate the code instead of duplicating it.

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

Do you have any idea ?

Thanks

+5  A: 

I would prefer to use the dispatch-dictionary idiom, coding something like...:

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)

Not sure what you think "code generation" would buy you to make it preferable to this kind of approach.

Alex Martelli
In the second line of code, you have a fullstop instead of a comma after 'map')
Geoffrey Van Wyk
Tx, edited and fixed.
Alex Martelli
With `modname = 'modulo.%s.views' % app` and `funname = app` it became exactly what I was looking for. Thanks
Natim
A: 

Why not just pass the function into specific function?

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)
Jack M.