1

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

1
  • "Generating" is probably not the way to go. Using some introspection is safer and easier. Commented May 19, 2010 at 18:01

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In the second line of code, you have a fullstop instead of a comma after 'map')
With modname = 'modulo.%s.views' % app and funname = app it became exactly what I was looking for. Thanks
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.