alternative way to import modules

9 views
Skip to first unread message

Robin B

unread,
Jan 8, 2009, 1:23:13 PM1/8/09
to web2py Web Framework
def mod_import(name):
mod = __import__(name)
for part in name.split('.')[1:]:
mod = getattr(mod,part)
return mod

T2 = mod_import('applications.%s.modules.t2'%request.application).T2
t2=T2(request,response,session,cache,T,db)
...

Benefits: does not modify sys.path and does not resort to exec'ing.

Robin

mdipierro

unread,
Jan 8, 2009, 1:49:50 PM1/8/09
to web2py Web Framework
what about ?

def mod_import(name,request=None):
if request: name='applications.%s.modules.%s' %
(request.application, name)
mod = __import__(name)
for part in name.split('.')[1:]:
mod = getattr(mod,part)
return mod

Robin B

unread,
Jan 8, 2009, 2:04:12 PM1/8/09
to web2py Web Framework

> def mod_import(name,request=None):
>   if request: name='applications.%s.modules.%s' %
> (request.application, name)
>   mod = __import__(name)
>   for part in name.split('.')[1:]:
>     mod = getattr(mod,part)
>   return mod

Nice, I like how t2 collects helpers under a single object without
polluting the global namespace. What if these helpers could be
collected under a single object like t2?

# in gluon/helpers.py or something
def mod_import(name):
mod = __import__(name)
for part in name.split('.')[1:]:
mod = getattr(mod,part)
return mod

class Helpers(...):
def __init__(self,request):
self.request = request

def import(self,name):
return mod_import('applications.%s.modules.%s'%
(self.request.application,name))

# in models/0.py
T2 = helpers.import('t2').T2

Yarko Tymciurak

unread,
Jan 8, 2009, 2:07:40 PM1/8/09
to web...@googlegroups.com
Ooooh! starting to look yummy...  :-)

Robin B

unread,
Feb 8, 2009, 6:38:52 PM2/8/09
to web2py Web Framework
Here is another version of mod_import() that does not use string
splitting:

def mod_import(name):
import sys
mod = sys.modules.get(name,None)
if mod is None:
__import__(name)
mod = sys.modules[name]
return mod

Robin

On Jan 8, 1:07 pm, "Yarko Tymciurak" <yark...@gmail.com> wrote:
> Ooooh! starting to look yummy...  :-)
>

mdipierro

unread,
Feb 8, 2009, 6:48:39 PM2/8/09
to web2py Web Framework
should this be in web2py? Pros/cons?

Massimo

Robin B

unread,
Feb 8, 2009, 7:09:42 PM2/8/09
to web2py Web Framework
I think so. Based on the way web2py applications should not modify
the sys.path, this kind of import should be encouraged.

Web2py utilities like this should be collected under one object in the
exec environment (eg. utils ).

my_apps_helpers = utils.import('helpers',request=request)

Robin

mdipierro

unread,
Feb 8, 2009, 7:49:14 PM2/8/09
to web2py Web Framework
I feel a patch coming.....

Massimo
Reply all
Reply to author
Forward
0 new messages