1010from pathlib import Path
1111from typing import IO , TypeAlias , final
1212
13- import yaml
13+ from ruamel .yaml import YAML
14+ from ruamel .yaml .error import YAMLError
1415from typing_extensions import override
15- from yaml import YAMLError
1616
1717from fairseq2 .utils .file import FileMode , FileSystem
1818
@@ -32,9 +32,12 @@ def dump(self, obj: object, output: Path | IO[str]) -> None: ...
3232
3333@final
3434class StandardYamlLoader (YamlLoader ):
35+ _yaml : YAML
3536 _file_system : FileSystem
3637
3738 def __init__ (self , file_system : FileSystem ) -> None :
39+ self ._yaml = YAML (typ = "safe" , pure = True )
40+
3841 self ._file_system = file_system
3942
4043 @override
@@ -47,16 +50,22 @@ def load(self, input_: Path | IO[str]) -> list[object]:
4750 finally :
4851 fp .close ()
4952
50- itr = yaml . safe_load_all (input_ )
53+ itr = self . _yaml . load_all (input_ )
5154
5255 return list (itr )
5356
5457
5558@final
5659class StandardYamlDumper (YamlDumper ):
60+ _yaml : YAML
5761 _file_system : FileSystem
5862
5963 def __init__ (self , file_system : FileSystem ) -> None :
64+ self ._yaml = YAML (typ = "safe" , pure = True )
65+
66+ self ._yaml .default_flow_style = False
67+ self ._yaml .sort_base_mapping_type_on_output = False # type: ignore[assignment]
68+
6069 self ._file_system = file_system
6170
6271 @override
@@ -69,8 +78,10 @@ def dump(self, obj: object, output: Path | IO[str]) -> None:
6978 finally :
7079 fp .close ()
7180 else :
72- yaml . safe_dump (obj , output , sort_keys = False )
81+ self . _yaml . dump (obj , output )
7382
7483
7584def read_yaml (s : str ) -> object :
76- return yaml .safe_load (s )
85+ yaml = YAML (typ = "safe" , pure = True )
86+
87+ return yaml .load (s )
0 commit comments