简体   繁体   中英

Loading empty dictionary when YAML file is empty (Python 3.4)

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?

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 (ie 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)
{}

At the top level a YAML file can have

  • a mapping, indicated by key value pairs separated by : (optionally in flow style using {} ),
  • a sequence indicated by - if it is block style and [ ] if it is flow style
  • a (single) scalar.

Your 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM