Reputation: 8846
I have a YAML file that is empty, and when I load it in, I would like to load it in as an empty dictionary. For example, I have
import yaml
with open('an_empty_file.yml', 'r') as config_file:
config=yaml.load(config_file)
print(config)
None
It turns out that yaml.load(config_file)
will return a NoneType
object, which I suppose makes sense. Is there an easy way to just return an empty dictionary?
Upvotes: 12
Views: 8489
Reputation: 76792
At the top level a YAML file can have
:
(optionally in flow style using {}
), -
if it is block style and [ ]
if it is flow styleYour file is not a mapping or a sequence, so it is a scalar and since the scalar with an empty representation is considered to be the same as specifying
null
in the file.
To load this as an empty dictionary and not as None you can do:
with open('an_empty_file.yml', 'r') as config_file:
config = yaml.load(config_file)
config = {} if config is None else config
print(config)
You should never try and take a short cut of doing:
config = yaml.load(config_file) or {}
as this would also cause files with the single scalar 0
:
0
with single scalar floats 0.0
:
0.0
with hex scalars 0x0
:
0x0
with an empty double quoted scalar ""
""
with an empty single quoted scalar ''
''
with an empty folded scalar:
>
with an empty literal style scalar:
|
with the single boolean False
:
False
or no
¹:
no
or off
¹:
off
as well as the empty sequence:
[
]
to result in config
to be an empty dictionary.
The number of different file contents that would be incorrectly changed to empty dictionaries is endless.
¹ This is a result of PyYAML never been updated for 1.1 to the 1.2 standard published in 2009. If it would be it would also convert octals of the form 0o0
.
Upvotes: 6
Reputation: 26600
If it returns None
, you can just use or
so your config will hold an empty dictionary by default if yaml.load
returns None:
config = yaml.load(config_file) or {}
Ultimately, what is happening here, starts from the left hand side:
We are right now assigning a value in to config. We are stating to assign yaml.load(config_file)
in to config, however, by using the or
, what we are saying in this statement is that, if it (yaml.load
) evaluates to a None or False condition (i.e. In this case for us, None), we will then assign {}
to config.
Quick demo taking an empty string as config_file:
>>> import yaml
>>> config_file = ''
>>> config = yaml.load(config_file) or {}
>>> print(config)
{}
Upvotes: 15