[Tutor] Trying to avoid using eval..

Steven D'Aprano steve at pearwood.info
Sat Feb 23 05:24:37 CET 2013


On 23/02/13 13:11, Rohit Mediratta wrote:
>
> Hi All,
>     I want to reload my Module after I fix bugs and want to instantiate an object of a class contained in this module.
>
> 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')
>
>
> Obviously, line 4 and line 6 dont work today.
> I want to know if there is any smart way to achieve this.
> In my previous life (Tcl), I could use 'eval' or 'set' to achieve this.


Untested:

def rerun(testBlock):
     modulename, classname = testBlock.split('.')
     module = __import__(modulename)
     reload(module)
     classobj = getattr(module, classname)
     return classobj()




-- 
Steven


More information about the Tutor mailing list