load_yaml_with_py_eval

  • full name: tenpy.tools.params.load_yaml_with_py_eval

  • parent module: tenpy.tools.params

  • type: function

tenpy.tools.params.load_yaml_with_py_eval(filename=None, yaml_content=None, context={'np': <module 'numpy' from '/home/docs/checkouts/readthedocs.org/user_builds/tenpy/envs/stable/lib/python3.11/site-packages/numpy/__init__.py'>})[source]

Load a yaml file with support for an additional !py_eval tag.

When defining yaml parameter files, it’s sometimes convenient to just have python snippets in there, e.g. to get fractions of pi or expand last lists.

This function loads a yaml file supporting such (short) python snippets that get evaluated by python’s eval(snippet).

It expects one string of python code following the !py_eval tag. The most reliable method to pass the python code is to use a literal string in yaml, as shown in the example below.

a: !py_eval |
    2**np.arange(6, 10)
b: !py_eval |
    [10, 15] + list(range(20, 31, 2)) + [35, 40]
c: !py_eval "2*np.pi * 0.3"

Note that a subsequent yaml.dump() might contain ugly parts if you construct generic python objects, e.g., a numpy array scalar like np.arange(10)[0]. If you want to avoid this, you can explicitly convert back to lists before.

Warning

Like pickle, it is not safe to load a yaml file from an untrusted source! A malicious file can call any Python function and should thus be treated with extreme caution.

Parameters:
  • filename (str | None) – Filename of the file to load.

  • yaml_content (str | None) – Alternatively to filename directly the content of the yaml file. Pass either filename or yaml_content.

  • context (dict) – The context of globals() passed to eval.

Returns:

Data (typically nested dictionary) as defined in the yaml file.

Return type:

config