Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of converting 'None' string to None

Let's say I have the following yaml file and the value in the 4th row should be None. How can I convert the 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, instead of simply doing:

if log_file_path == 'None':
  log_file_path = None
like image 288
bmpasini Avatar asked Mar 14 '23 06:03

bmpasini


1 Answers

The None value in your YAML file is not really kosher YAML since YAML it uses absence of a value to represent None. So if you just used proper YAML your troubles would be over:

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

Notice how it read the absence of the LOG_FILE_PATH as None rather than 'None'.

Later edit: Other values which also work are: null, Null and NULL as per: https://yaml.org/type/null.html

like image 189
Oin Avatar answered Mar 19 '23 03:03

Oin