[Tutor] Trying to avoid using eval..

eryksun eryksun at gmail.com
Sat Feb 23 05:35:54 CET 2013

On Fri, Feb 22, 2013 at 9:11 PM, Rohit Mediratta <rohit_medi at hotmail.com> wrote:
> Heres the pseudo code of what I want to do:
> def rerun(testBlock) :
>     op = testBlock.split('.')
>     module = op[0] ; className = op[1]
>     reload(module)
>     # testBlock is a string, so it needs evaluation!
>     newObject = testBlock()
> rerun('ModuleName.className')

You can use __import__, and extend it to handle packages:

except NameError:
    from imp import reload  # 3.x

def rerun(clsPath, *args):
    modPath, clsName = clsPath.rsplit('.', 1)
    mod = __import__(modPath, fromlist='not empty')
    cls = getattr(mod, clsName)
    return cls(*args)

The fromlist option only cares whether or not the sequence is empty.
If it's not empty you get the leaf (e.g. 'xml.etree.ElementTree' =>
ElementTree). If it's empty you get the base package (e.g.
'xml.etree.ElementTree' => xml).

More information about the Tutor mailing list