Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

dynamic class that returns given "fallback" value when AttributeError

$
0
0

I got a dynamic class (with attributes) from the contents of a YAML file to use as a configuration object. The problem is that the code (which uses this class) can ask for an attribute that has not been defined in the YAML file which then causes an AttributeError.

Is there an "easy" way to implement (probably via modifying getattr as that is going to be called when the attribute can't be found, correct?) to hand that class upon calling it a fallback value that should be returned in case the requested attribute does not exist (= on AttributeError)?

Somewhat like this:

def dc_getattr(fallback):   return fallbackdynamic_class = type(str_test_class,   (object,),   {"__getattr__": dc_getattr(fallback),'ATTR_1' : {'key1':123,'key2':456,},   })

goal:

DC = dynamic_class()print(DC.ATTR_1['key1'])                       # return: '123'print(DC.NO_ATTR(fallback = 'my fallback'))    # return: 'my fallback'

Thanks!


PS: for the bigger context the code that turns a YAML derived dict() into a config-class object, with the ability to have access to dynamic YAML configuration content:

def return_subcfg_class(dct_subcfg,cnt_depth,str_cfggrp='config group'):"""   self referencing (recursive) "walker" that exhausts   the dict config (tree) being handed over   keeps track of the depth"""   cnt_depth += 1   dct_cfgclass = {}   for key in dct_subcfg.keys():      key_attr = key.upper()      if type(dct_subcfg[key]) != dict:         dct_cfgclass[key_attr] = dct_subcfg[key]      else: # we got a subsection -> new type()         dct_suboptns = return_subcfg_class(dct_subcfg[key],cnt_depth)         if str_cfggrp in dct_subcfg[key].keys(): #             key_cfggrp = dct_subcfg[key][str_cfggrp].upper()            if key_cfggrp in dct_cfgclass.keys(): # cfggrp already exists, add               dct_cfgclass[key_cfggrp][key] = type(key,(object,),dct_suboptns)            else: # cfggrp is new, create from scratch               dct_cfgclass[key_cfggrp] = {key:type(key,(object,),dct_suboptns)}         else:            dct_cfgclass[key_attr] = type(key,(object,),dct_suboptns)   return dct_cfgclassdef return_cfg_class(los_configFile,str_cfggrp='config group'):"""   return config class/dict"""   str_configFolder,str_configFile = los_configFile   dct_config = return_dct_from_yaml(str_configFolder,str_configFile)   dct_cfg = return_subcfg_class(dct_config,0)   cls_cfg = type('app_config',(object,),dct_cfg)   return cls_cfg

called like this:CFG = return_cfg_class(['.',str_configFile_app_yml])

used like this:str_url = CFG.RL['FTP'].URL

YAML:

http:  config group: 'RL'  url:'www.stackoverflow.com'ftp:  config group: 'RL'  url:'www.stackoverflow.com'

I tried modifying getattr and init and looked at search results via google (lots of SO results, but none helped).. but the particular problem of having a class return a dynamically specified value upon AttributeError doesn't seem to be encountered or I don't know how it is called?


Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>