aboutsummaryrefslogtreecommitdiffstats
path: root/python/attr/converters.py
diff options
context:
space:
mode:
authorJames Taylor <user234683@users.noreply.github.com>2019-02-16 23:41:52 -0800
committerJames Taylor <user234683@users.noreply.github.com>2019-02-16 23:41:52 -0800
commit3905e7e64059b45479894ba1fdfb0ef9cef64475 (patch)
tree4c5dbbfd204d0351cac8412cc87a65fea49c1a52 /python/attr/converters.py
parent24642455d0dc5841ddec99f456598c4f763c1e8a (diff)
downloadyt-local-3905e7e64059b45479894ba1fdfb0ef9cef64475.tar.lz
yt-local-3905e7e64059b45479894ba1fdfb0ef9cef64475.tar.xz
yt-local-3905e7e64059b45479894ba1fdfb0ef9cef64475.zip
basic subscriptions system
Diffstat (limited to 'python/attr/converters.py')
-rw-r--r--python/attr/converters.py78
1 files changed, 78 insertions, 0 deletions
diff --git a/python/attr/converters.py b/python/attr/converters.py
new file mode 100644
index 0000000..37c4a07
--- /dev/null
+++ b/python/attr/converters.py
@@ -0,0 +1,78 @@
+"""
+Commonly useful converters.
+"""
+
+from __future__ import absolute_import, division, print_function
+
+from ._make import NOTHING, Factory
+
+
+def optional(converter):
+ """
+ A converter that allows an attribute to be optional. An optional attribute
+ is one which can be set to ``None``.
+
+ :param callable converter: the converter that is used for non-``None``
+ values.
+
+ .. versionadded:: 17.1.0
+ """
+
+ def optional_converter(val):
+ if val is None:
+ return None
+ return converter(val)
+
+ return optional_converter
+
+
+def default_if_none(default=NOTHING, factory=None):
+ """
+ A converter that allows to replace ``None`` values by *default* or the
+ result of *factory*.
+
+ :param default: Value to be used if ``None`` is passed. Passing an instance
+ of :class:`attr.Factory` is supported, however the ``takes_self`` option
+ is *not*.
+ :param callable factory: A callable that takes not parameters whose result
+ is used if ``None`` is passed.
+
+ :raises TypeError: If **neither** *default* or *factory* is passed.
+ :raises TypeError: If **both** *default* and *factory* are passed.
+ :raises ValueError: If an instance of :class:`attr.Factory` is passed with
+ ``takes_self=True``.
+
+ .. versionadded:: 18.2.0
+ """
+ if default is NOTHING and factory is None:
+ raise TypeError("Must pass either `default` or `factory`.")
+
+ if default is not NOTHING and factory is not None:
+ raise TypeError(
+ "Must pass either `default` or `factory` but not both."
+ )
+
+ if factory is not None:
+ default = Factory(factory)
+
+ if isinstance(default, Factory):
+ if default.takes_self:
+ raise ValueError(
+ "`takes_self` is not supported by default_if_none."
+ )
+
+ def default_if_none_converter(val):
+ if val is not None:
+ return val
+
+ return default.factory()
+
+ else:
+
+ def default_if_none_converter(val):
+ if val is not None:
+ return val
+
+ return default
+
+ return default_if_none_converter