<s> from __future__ import absolute_import <EOL> from __future__ import unicode_literals <EOL> import logging <EOL> from string import Template <EOL> import six <EOL> from . errors import ConfigurationError <EOL> log = logging . getLogger ( __name__ ) <EOL> def interpolate_environment_variables ( config , section , environment ) : <EOL> def process_item ( name , config_dict ) : <EOL> return dict ( <EOL> ( key , interpolate_value ( name , key , val , section , environment ) ) <EOL> for key , val in ( config_dict or { } ) . items ( ) <EOL> ) <EOL> return dict ( <EOL> ( name , process_item ( name , config_dict or { } ) ) <EOL> for name , config_dict in config . items ( ) <EOL> ) <EOL> def interpolate_value ( name , config_key , value , section , mapping ) : <EOL> try : <EOL> return recursive_interpolate ( value , mapping ) <EOL> except InvalidInterpolation as e : <EOL> raise ConfigurationError ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' . format ( <EOL> config_key = config_key , <EOL> name = name , <EOL> section = section , <EOL> string = e . string ) ) <EOL> def recursive_interpolate ( obj , mapping ) : <EOL> if isinstance ( obj , six . string_types ) : <EOL> return interpolate ( obj , mapping ) <EOL> elif isinstance ( obj , dict ) : <EOL> return dict ( <EOL> ( key , recursive_interpolate ( val , mapping ) ) <EOL> for ( key , val ) in obj . items ( ) <EOL> ) <EOL> elif isinstance ( obj , list ) : <EOL> return [ recursive_interpolate ( val , mapping ) for val in obj ] <EOL> else : <EOL> return obj <EOL> def interpolate ( string , mapping ) : <EOL> try : <EOL> return Template ( string ) . substitute ( mapping ) <EOL> except ValueError : <EOL> raise InvalidInterpolation ( string ) <EOL> class InvalidInterpolation ( Exception ) : <EOL> def __init__ ( self , string ) : <EOL> self . string = string </s>
