Skip to content

Commit e244703

Browse files
author
Sylvain MARIE
committed
Most type hints have been fixed, in particular for @yaml_info. Fixes #11
1 parent 63d26d8 commit e244703

3 files changed

Lines changed: 26 additions & 20 deletions

File tree

yamlable/base.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33

44
try:
55
# Python 2 only:
6-
from StringIO import StringIO
6+
from StringIO import StringIO as _StringIO # type: ignore # noqa
77

88
# create a variant that can serve as a context manager
9-
class StringIO(StringIO):
9+
class StringIO(_StringIO):
1010
def __enter__(self):
1111
return self
1212

@@ -15,7 +15,7 @@ def __exit__(self, exception_type, exception_value, traceback):
1515

1616
except ImportError:
1717
# (IOBase is only used in type hints)
18-
from io import IOBase, StringIO
18+
from io import IOBase, StringIO # type: ignore
1919

2020
from warnings import warn
2121

@@ -57,7 +57,7 @@ def __to_yaml_dict__(self):
5757
if 'to_yaml_dict' in dir(self):
5858
warn(type(self).__name__ + " still uses the legacy method name 'to_yaml_dict'. This name will not be "
5959
"supported in future version, please use '__to_yaml_dict__' instead")
60-
return self.to_yaml_dict()
60+
return self.to_yaml_dict() # type: ignore
6161

6262
# Default: return vars(self) (Note: no need to make a copy, pyyaml does not modify it)
6363
return vars(self)
@@ -86,13 +86,13 @@ def __from_yaml_dict__(cls, # type: Type[Y]
8686
if 'from_yaml_dict' in dir(cls):
8787
warn(cls.__name__ + " still uses the legacy method name 'from_yaml_dict'. This name will not be "
8888
"supported in future version, please use '__from_yaml_dict__' instead")
89-
return cls.from_yaml_dict(dct, yaml_tag)
89+
return cls.from_yaml_dict(dct, yaml_tag) # type: ignore
9090

9191
# Default: call constructor with all keyword arguments
92-
return cls(**dct)
92+
return cls(**dct) # type: ignore
9393

9494
def dump_yaml(self,
95-
file_path_or_stream, # type: Union[str, IOBase, StrinIO]
95+
file_path_or_stream, # type: Union[str, IOBase, StringIO]
9696
safe=True, # type: bool
9797
**pyyaml_kwargs # type: Any
9898
):
@@ -113,7 +113,7 @@ def dump_yaml(self,
113113
else:
114114
dump(self, f, **pyyaml_kwargs)
115115
else:
116-
with file_path_or_stream as f:
116+
with file_path_or_stream as f: # type: ignore
117117
if safe:
118118
safe_dump(self, f, **pyyaml_kwargs)
119119
else:
@@ -175,7 +175,7 @@ def load_yaml(cls, # type: Type[Y]
175175
else:
176176
res = load(f.read())
177177
else:
178-
with file_path_or_stream as f:
178+
with file_path_or_stream as f: # type: ignore
179179
if safe:
180180
res = safe_load(f.read())
181181
else:

yamlable/main.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import six
55

66
try: # python 3.5+
7-
from typing import TypeVar, Callable, Optional, Iterable, Any, Tuple, Mapping, Any, Dict
7+
from typing import TypeVar, Callable, Optional, Iterable, Any, Tuple, Mapping, Any, Dict, Set, List
88
YA = TypeVar('YA', bound='YamlAble')
99
T = TypeVar('T')
1010
except ImportError:
@@ -97,7 +97,7 @@ def is_yaml_tag_supported(cls,
9797
def yaml_info(yaml_tag=None, # type: str
9898
yaml_tag_ns=None # type: str
9999
):
100-
# type: (...) -> Callable[[Type[YA], Optional[str], Optional[str]], Type[YA]]
100+
# type: (...) -> Callable[[Type[YA]], Type[YA]]
101101
"""
102102
A simple class decorator to tag a class with a global yaml tag - that way you do not have to call `YamlAble` super
103103
constructor.
@@ -132,7 +132,9 @@ class Foo(YamlAble):
132132
:param yaml_tag_ns: the yaml namespace. It will be appended with '.<cls.__name__>'
133133
:return:
134134
"""
135-
def f(cls):
135+
def f(cls # type: Type[YA]
136+
):
137+
# type: (...) -> Type[YA]
136138
return yaml_info_decorate(cls, yaml_tag=yaml_tag, yaml_tag_ns=yaml_tag_ns)
137139
return f
138140

@@ -180,9 +182,13 @@ class Foo(YamlAble):
180182
if yaml_tag_ns is not None:
181183
if yaml_tag is not None:
182184
raise ValueError("Only one of 'yaml_tag' and 'yaml_tag_ns' should be provided")
183-
# default: append the class name
185+
186+
# create yaml_tag by appending the class name to the namespace
184187
yaml_tag = yaml_tag_ns + '.' + cls.__name__
185188

189+
elif yaml_tag is None:
190+
raise ValueError("One non-None `yaml_tag` or `yaml_tag_ns` must be provided.")
191+
186192
if issubclass(cls, YamlObject2):
187193
if not yaml_tag.startswith('!'):
188194
raise ValueError("When extending YamlObject2, the `yaml_tag` field should contain the full yaml tag, "
@@ -193,7 +199,7 @@ class Foo(YamlAble):
193199
if yaml_tag.startswith('!'):
194200
raise ValueError("When extending YamlAble, the `yaml_tag` field should only contain the yaml tag suffix, "
195201
"and should therefore NOT start with !")
196-
cls.__yaml_tag_suffix__ = yaml_tag
202+
cls.__yaml_tag_suffix__ = yaml_tag # type: ignore
197203
else:
198204
raise TypeError("classes tagged with @yaml_info should be subclasses of YamlAble or YamlObject2")
199205

@@ -263,10 +269,10 @@ def encode_yamlable(dumper,
263269

264270

265271
try: # PyYaml 5.1+
266-
from yaml import FullLoader, UnsafeLoader
267-
ALL_PYYAML_LOADERS = (Loader, SafeLoader, FullLoader, UnsafeLoader)
272+
from yaml import FullLoader
273+
ALL_PYYAML_LOADERS = (Loader, SafeLoader, FullLoader)
268274
except ImportError:
269-
ALL_PYYAML_LOADERS = (Loader, SafeLoader)
275+
ALL_PYYAML_LOADERS = (Loader, SafeLoader) # type: ignore
270276

271277

272278
ALL_PYYAML_DUMPERS = (Dumper, SafeDumper)
@@ -322,7 +328,7 @@ def _get_all_subclasses(typ, # type: Type[T]
322328
sub_list = typ.__subclasses__()
323329

324330
# recurse
325-
result = []
331+
result = [] # type: List[Type[T]]
326332
for t in sub_list:
327333
# only keep the origins in the list
328334
# to = get_origin(t) or t

yamlable/yaml_objects.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class YAMLObjectMetaclassStrict(YAMLObjectMetaclass):
2222
"""
2323
Improved metaclass for YAMLObject, that raises an error if yaml_tag is not defined
2424
"""
25-
def __init__(cls, # type: Type[YO2]
25+
def __init__(cls, # type: Type[YO2] # type: ignore
2626
name, bases, kwds):
2727

2828
# construct as usual
@@ -108,4 +108,4 @@ def from_yaml(cls, # type: Type[YamlObject2]
108108
:return:
109109
"""
110110
constructor_args = read_yaml_node_as_dict(loader, node)
111-
return cls.__from_yaml_dict__(constructor_args, yaml_tag=cls.yaml_tag)
111+
return cls.__from_yaml_dict__(constructor_args, yaml_tag=cls.yaml_tag) # type: ignore

0 commit comments

Comments
 (0)