module importing and variable syntax

Steve Purcell stephen_purcell at yahoo.com
Tue Mar 13 05:46:24 EST 2001


Jeff Davis wrote:
> I was previously a perl user, but now I am taking an interest in python. 

Hurrah!

> Module importing doesn't take a string argument, but just a "bare word" 
> (in perl terms). This means I have to know the name of the file in 
> advance, and it needs to be in the right directory, or I need to use eval().

You can import a module with a given name as follows:

  the_module = __import__('the_module_name')

If you need to get named items out of the module later you can use 'getattr':

  o = getattr(the_module, 'item_name')
  o.square()

> [snip] Right now the 
> concatenation of strings can be annoying compared to just (perl) 
> '$string = "a $anotherstring be";', but for a lot of programs it is well 
> worth the tradeoff.


You can try

  the_string = "a %(anotherstring)s be" % locals()

to get a similar effect but with the additional safety of an exception being
raised if 'anotherstring' is not in the current namespace.

-Steve


-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo




More information about the Python-list mailing list