Pythonic way to convert the string "None" to None

Let's say I have the following yaml file, and the value in the 4th line should be None. How to convert string 'None'to None?

CREDENTIALS:
  USERNAME: 'USERNAME'
  PASSWORD: 'PASSWORD'
LOG_FILE_PATH: None <----------

I already have this:

config = yaml.safe_load(open(config_path, "r"))
username, password, log_file_path = (config['CREDENTIALS']['USERNAME'],
                                     config['CREDENTIALS']['PASSWORD'],
                                     config['LOG_FILE_PATH'])

I would like to know if there is a pythonic way to do this, and not just do:

if log_file_path == 'None':
  log_file_path = None
+4
source share
1 answer

The value Nonein your YAML file is not really kosher YAML, since it uses the absence of a value to represent None. Therefore, if you just used the correct YAML, your problems would end:

In [7]: yaml.load("""
   ...: CREDENTIALS:
   ...:   USERNAME: 'USERNAME'
   ...:   PASSWORD: 'PASSWORD'
   ...: LOG_FILE_PATH: 
   ...: """)
Out[7]: 
{'CREDENTIALS': {'PASSWORD': 'PASSWORD', 'USERNAME': 'USERNAME'},
 'LOG_FILE_PATH': None}

Pay attention to how he reads the absence of LOG_FILE_PATHboth None, and not 'None'.

+7
source

Source: https://habr.com/ru/post/1629254/


All Articles