44"""YAML serialization is routed through here to centralize common logic."""
55
66import sys
7+ import warnings
8+
9+
10+ def multiline_str_representer (dumper , data ):
11+ if len (data .splitlines ()) > 1 :
12+ return dumper .represent_scalar ("tag:yaml.org,2002:str" , data , style = "|" )
13+ else :
14+ return dumper .represent_scalar ("tag:yaml.org,2002:str" , data )
15+
716
817try :
9- import yaml
18+ from yaml import YAMLObject , add_representer
19+
20+ add_representer (str , multiline_str_representer )
1021except ModuleNotFoundError as e :
11- raise ModuleNotFoundError (
12- f"This tool requires PyYAML but it was not installed. "
13- f"Recommend: { sys .executable } -m pip install PyYAML"
14- ) from e
22+ warnings .warn (
23+ "PyYAML is not installed; you will not be able to generate linalg yaml definitions."
24+ )
1525
16- __all__ = [
17- "yaml_dump" ,
18- "yaml_dump_all" ,
19- "YAMLObject" ,
20- ]
26+ class YAMLObject :
27+ pass
2128
2229
23- class YAMLObject (yaml . YAMLObject ):
30+ class YAMLObject (YAMLObject ):
2431 @classmethod
2532 def to_yaml (cls , dumper , self ):
2633 """Default to a custom dictionary mapping."""
@@ -33,21 +40,34 @@ def as_linalg_yaml(self):
3340 return yaml_dump (self )
3441
3542
36- def multiline_str_representer (dumper , data ):
37- if len (data .splitlines ()) > 1 :
38- return dumper .represent_scalar ("tag:yaml.org,2002:str" , data , style = "|" )
39- else :
40- return dumper .represent_scalar ("tag:yaml.org,2002:str" , data )
43+ def yaml_dump (data , sort_keys = False , ** kwargs ):
44+ try :
45+ import yaml
4146
47+ return yaml .dump (data , sort_keys = sort_keys , ** kwargs )
48+ except ModuleNotFoundError as e :
49+ raise ModuleNotFoundError (
50+ f"This tool requires PyYAML but it was not installed. "
51+ f"Recommend: { sys .executable } -m pip install PyYAML"
52+ ) from e
4253
43- yaml .add_representer (str , multiline_str_representer )
4454
55+ def yaml_dump_all (data , sort_keys = False , explicit_start = True , ** kwargs ):
56+ try :
57+ import yaml
4558
46- def yaml_dump (data , sort_keys = False , ** kwargs ):
47- return yaml .dump (data , sort_keys = sort_keys , ** kwargs )
59+ return yaml .dump_all (
60+ data , sort_keys = sort_keys , explicit_start = explicit_start , ** kwargs
61+ )
62+ except ModuleNotFoundError as e :
63+ raise ModuleNotFoundError (
64+ f"This tool requires PyYAML but it was not installed. "
65+ f"Recommend: { sys .executable } -m pip install PyYAML"
66+ ) from e
4867
4968
50- def yaml_dump_all (data , sort_keys = False , explicit_start = True , ** kwargs ):
51- return yaml .dump_all (
52- data , sort_keys = sort_keys , explicit_start = explicit_start , ** kwargs
53- )
69+ __all__ = [
70+ "yaml_dump" ,
71+ "yaml_dump_all" ,
72+ "YAMLObject" ,
73+ ]
0 commit comments