0

I have used the fix presented in YAML loads 5e-6 as string and not a number to correctly load into python numbers represented in scientific notation in a yaml file.

I also have complex numbers in my yaml file. These numbers may have varying amounts of whitespace (e.g., 2+2j, or 2 + 2j, etc). The complex numbers are currently being read in as strings (in the same way that the numbers in scientific notation were read in as strings prior to the fix referenced above). I would like to know how to modify the add_implicit_resolver argument in the fix to correctly read in complex numbers. Ideally, I'd like to continue to use pyyaml.

More specifically, if I have an entry in my yaml file such as:

offset: 2 + 1j

I would like this to be recognized as the complex number (of class 'complex'):

2+1j

Currently, the value in the python dictionary corresponding to the key 'offset' is a string:

'2 + 1j'

which I have to manually convert into a complex number via:

complex('2 + 1j'.replace(' ', ''))

I'm looking to automate this process by modifying the argument to the add_implicit_resolver using the same strategy as in the link above for dealing with numbers in scientific notation.

As for a spec, yes, in general, the real and imaginary parts of the complex number may be in scientific notation: (e.g., ' 2e-3 + 1.3e-4j'). I am fine with restricting the format to have a trailing j for the imaginary part. No tabs, no linefeeds, just individual spaces. Real or imaginary part can be missing and can be expressed as integers or floats.

rhz
  • 960
  • 14
  • 29
  • Do you want to use pyyaml or ruamel.yaml? Or don't care? – wim Jan 07 '20 at 22:58
  • Edited question to indicate preference for pyyaml. – rhz Jan 07 '20 at 23:24
  • I hope you are aware that YAML doesn't allow spaces between sign and digits in the regular expressions for [integers](https://yaml.org/type/int.html)/[floats](https://yaml.org/type/float.html) – Anthon Jan 08 '20 at 10:06
  • 1
    Examples don't make up for a missing specification. What exactly do you want to recognize? Can each numeric part include decimals, can they be in scientific notation, how much and what kinds of whitespace (space, tab, linefeed, …) are you willing to allow, can `j` be replaced by the more common `i`, can the real part be missing (e.g. `2j`)? – flyx Jan 08 '20 at 13:17
  • Edited question to provide more detailed spec. – rhz Jan 08 '20 at 18:13
  • For those that don't have a preference with libraries and can control how the yamls are constructed, ruamel.yaml's unsafe constructor implements complex numbers as save-able objects. Simply use `YAML(typ='unsafe')` – Daniel Jun 30 '23 at 17:44

0 Answers0