__import__ with dict values

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Mar 13 06:20:02 CET 2009


En Thu, 12 Mar 2009 23:00:30 -0200, alex goretoy  
<aleksandr.goretoy at gmail.com> escribió:

> Thank you. This makes sense to me. I will go with sys.modules. Can you  
> give
> me a good example how to do it getattr way?

obj.attr is the same as getattr(obj, "attr") (note the quotes). This makes  
more sense when you don't know the attribute name in advance: getattr(obj,  
some_variable_containing_the_attribute_name)

If you find yourself using eval in this way: eval("leftpart.%s" %  
rightpart) replace it with getattr(leftpart, rightpart).

This statement:
 from logging import ERROR
becomes:
logging = __import__("logging")
ERROR = getattr(logging, "ERROR")

(except that the intermediate "logging" variable doesn't exist in the  
first case).


> currently I am having this problem in my code. Kinda off subject, but not
> entirely. I set default variable in self.opt after that I import
> jar.properties into self.opt['properties']. Now my self.opt doesn't have  
> the
> same defaults set. in other words we load our configuration properties.  
> Then
> we over write any configuration properties with supplied sys.argv[1::]
> arguments I am passing my sys.argv to a class and inside the class I use
> getopt to get site_name and files_name, also many other variable that
> overwrite the configuration that is set from the jar.properties
>
> This was working when I was using exec and eval. I was not able to just  
> use
> exec I had to use exec on import and eval on module.module it was wierd,  
> can
> someone tell me why?

Quoting myself from last post:

>> If you think you have to use eval: you don't. Never.

Same is valid for exec. There are very few cases when exec/eval is really  
the right thing to do. If you build an expression "x.y" just to eval() it,  
use getattr instead, as above. Same for exec´ing "x.y = z" - use  
setattr(x, "y", z) instead.

-- 
Gabriel Genellina




More information about the Python-list mailing list