Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possibly wrong type annotations in register_structure_hook_factory #281

Closed
sscherfke opened this issue Jun 30, 2022 · 6 comments
Closed

Comments

@sscherfke
Copy link

  • cattrs version: 22.1.0
  • Python version: 3.10
  • Operating System: macOS

Description

It seems like the type annotations for Converter.register_structue_hook_factory() are not correct.

They suggest a function signature that, when applied, leads to errors in my tests.

What I Did

My code:

def register_attrs_hook_factory(converter: Converter) -> None:
    """
    Register a hook factory that allows using instances of attrs classes where
    cattrs would normally expect a dictionary.

    These instances are then returned as-is and without further processing.
    """

    def allow_attrs_instances(typ: Any) -> Callable[[Any, Any], Any]:
        # According to mypy, this should be:
        # def structure_attrs(val: Any) -> Any:
        def structure_attrs(val: Any, _: Any) -> Any: 
            if isinstance(val, typ):
                return val
            return converter.structure_attrs_fromdict(val, typ)

        return structure_attrs

    converter.register_structure_hook_factory(has, allow_attrs_instances)  # mypy complains here

Mypy complains when I do def structure_attrs(val: Any, _: Any) -> Any:

src/typed_settings/converters.py:77: error: Argument 2 to "register_structure_hook_factory" of "Converter" 
has incompatible type "Callable[[Any], Callable[[Any, Any], Any]]"; 
expected "Callable[[Any], Callable[[Any], Any]]"  [arg-type]

But pytest complains when I do def structure_attrs(val: Any) -> Any:

typed_settings.exceptions.InvalidValueError: structure_attrs() takes 1 positional argument but 2 were given

IMHO, pytest has the stronger arguments. ;-)

@Tinche
Copy link
Member

Tinche commented Jul 4, 2022

I think you might be right, actually.

Fact of the matter is, the insides of cattrs aren't checked with Mypy since Mypy is far from being able to handle what we need at time this. So the type hints are essentially just inline type stubs. Hence the preponderence of Any.

@Tinche Tinche closed this as completed in 38205da Jul 4, 2022
@Tinche
Copy link
Member

Tinche commented Jul 4, 2022

@sscherfke I applied a fix to main, check if it's good for you now?

@sscherfke
Copy link
Author

I will try it. There might be other, similar places at well. I’ll check it.

@Tinche
Copy link
Member

Tinche commented Jul 4, 2022

Bring em forward and we'll iron them out.

Tinche added a commit that referenced this issue Jul 6, 2022
@sscherfke
Copy link
Author

Looks like I need to create a PR .. 😬

@sscherfke
Copy link
Author

Maybe this?

diff --git a/src/cattrs/_compat.py b/src/cattrs/_compat.py
index c8e77cd..6f324cb 100644
--- a/src/cattrs/_compat.py
+++ b/src/cattrs/_compat.py
@@ -163,17 +163,17 @@ if is_py37 or is_py38:
             or (type.__origin__ in (Tuple, tuple) and type.__args__[1] is ...)
         )
 
-    def is_mutable_set(type):
+    def is_mutable_set(type: Any) -> bool:
         return type is set or (
             type.__class__ is _GenericAlias and issubclass(type.__origin__, MutableSet)
         )
 
-    def is_frozenset(type):
+    def is_frozenset(type: Any) -> bool:
         return type is frozenset or (
             type.__class__ is _GenericAlias and issubclass(type.__origin__, FrozenSet)
         )
 
-    def is_mapping(type):
+    def is_mapping(type: Any) -> bool:
         return type in (TypingMapping, dict) or (
             type.__class__ is _GenericAlias
             and issubclass(type.__origin__, TypingMapping)
@@ -192,7 +192,7 @@ if is_py37 or is_py38:
     def is_bare(type):
         return getattr(type, "__args__", None) in bare_generic_args
 
-    def is_counter(type):
+    def is_counter(type: Any) -> bool:
         return (
             type in (Counter, ColCounter)
             or getattr(type, "__origin__", None) is ColCounter
@@ -201,15 +201,15 @@ if is_py37 or is_py38:
     if is_py38:
         from typing import Literal
 
-        def is_literal(type) -> bool:
+        def is_literal(type: Any) -> bool:
             return type.__class__ is _GenericAlias and type.__origin__ is Literal
 
     else:
         # No literals in 3.7.
-        def is_literal(_) -> bool:
+        def is_literal(_: Any) -> bool:
             return False
 
-    def is_generic(obj):
+    def is_generic(obj: Any) -> bool:
         return isinstance(obj, _GenericAlias)
 
     def copy_with(type, args):
@@ -240,12 +240,12 @@ else:
         # Not present on 3.9.0, so we try carefully.
         from typing import _LiteralGenericAlias
 
-        def is_literal(type) -> bool:
+        def is_literal(type: Any) -> bool:
             return type.__class__ is _LiteralGenericAlias
 
     except ImportError:
 
-        def is_literal(_) -> bool:
+        def is_literal(_: Any) -> bool:
             return False
 
     Set = AbcSet
@@ -329,7 +329,7 @@ else:
             or (origin is tuple and type.__args__[1] is ...)
         )
 
-    def is_mutable_set(type):
+    def is_mutable_set(type: Any) -> bool:
         return (
             type in (TypingSet, TypingMutableSet, set)
             or (
@@ -339,7 +339,7 @@ else:
             or (getattr(type, "__origin__", None) in (set, AbcMutableSet, AbcSet))
         )
 
-    def is_frozenset(type):
+    def is_frozenset(type: Any) -> bool:
         return (
             type in (FrozenSet, frozenset)
             or (
@@ -349,12 +349,12 @@ else:
             or (getattr(type, "__origin__", None) is frozenset)
         )
 
-    def is_bare(type):
+    def is_bare(type: Any) -> bool:
         return isinstance(type, _SpecialGenericAlias) or (
             not hasattr(type, "__origin__") and not hasattr(type, "__args__")
         )
 
-    def is_mapping(type):
+    def is_mapping(type: Any) -> bool:
         return (
             type in (TypingMapping, Dict, TypingMutableMapping, dict, AbcMutableMapping)
             or (
@@ -368,13 +368,13 @@ else:
             or issubclass(type, dict)
         )
 
-    def is_counter(type):
+    def is_counter(type: Any) -> bool:
         return (
             type in (Counter, TypingCounter)
             or getattr(type, "__origin__", None) is Counter
         )
 
-    def is_generic(obj):
+    def is_generic(obj: Any) -> bool:
         return isinstance(obj, _GenericAlias) or isinstance(obj, GenericAlias)
 
     def copy_with(type, args):
@@ -385,5 +385,5 @@ else:
         return type.__origin__[args]
 
 
-def is_generic_attrs(type):
+def is_generic_attrs(type: Any) -> bool:
     return is_generic(type) and has(type.__origin__)
diff --git a/src/cattrs/converters.py b/src/cattrs/converters.py
index 6dd4d3e..6cc40ac 100644
--- a/src/cattrs/converters.py
+++ b/src/cattrs/converters.py
@@ -55,6 +55,12 @@ NoneType = type(None)
 T = TypeVar("T")
 V = TypeVar("V")
 
+PredicateFn = Callable[[Type[T]], bool]
+StructureFn = Callable[[Any, Type[T]], int]
+StructureFnFactory = Callable[[Type[T]], StructureFn]
+UnstructureFn = Callable[[T], Any]
+UnstructureFnFactory = Callable[[Type[T]], UnstructureFn]
+
 
 class UnstructureStrategy(Enum):
     """`attrs` classes unstructuring strategies."""
@@ -182,7 +188,7 @@ class BaseConverter:
         self._dict_factory = dict_factory
 
         # Unions are instances now, not classes. We use different registries.
-        self._union_struct_registry: Dict[Any, Callable[[Any, Type[T]], T]] = {}
+        self._union_struct_registry: Dict[Any, StructureFn] = {}
 
     def unstructure(self, obj: Any, unstructure_as: Any = None) -> Any:
         return self._unstructure_func.dispatch(
@@ -198,7 +204,7 @@ class BaseConverter:
             else UnstructureStrategy.AS_TUPLE
         )
 
-    def register_unstructure_hook(self, cls: Any, func: Callable[[Any], Any]) -> None:
+    def register_unstructure_hook(self, cls: Any, func: UnstructureFn) -> None:
         """Register a class-to-primitive converter function for a class.
 
         The converter function should take an instance of the class and return
@@ -212,7 +218,7 @@ class BaseConverter:
             self._unstructure_func.register_cls_list([(cls, func)])
 
     def register_unstructure_hook_func(
-        self, check_func: Callable[[Any], bool], func: Callable[[T], Any]
+        self, check_func: PredicateFn, func: UnstructureFn
     ):
         """Register a class-to-primitive converter function for a class, using
         a function to check if it's a match.
@@ -220,9 +226,7 @@ class BaseConverter:
         self._unstructure_func.register_func_list([(check_func, func)])
 
     def register_unstructure_hook_factory(
-        self,
-        predicate: Callable[[Any], bool],
-        factory: Callable[[Any], Callable[[Any], Any]],
+        self, predicate: PredicateFn, factory: UnstructureFnFactory
     ) -> None:
         """
         Register a hook factory for a given predicate.
@@ -235,7 +239,7 @@ class BaseConverter:
         """
         self._unstructure_func.register_func_list([(predicate, factory, True)])
 
-    def register_structure_hook(self, cl: Any, func: Callable[[Any, Type[T]], T]):
+    def register_structure_hook(self, cl: Any, func: StructureFn):
         """Register a primitive-to-class converter function for a type.
 
         The converter function should take two arguments:
@@ -253,18 +257,14 @@ class BaseConverter:
         else:
             self._structure_func.register_cls_list([(cl, func)])
 
-    def register_structure_hook_func(
-        self, check_func: Callable[[Type[T]], bool], func: Callable[[Any, Type[T]], T]
-    ):
+    def register_structure_hook_func(self, check_func: PredicateFn, func: StructureFn):
         """Register a class-to-primitive converter function for a class, using
         a function to check if it's a match.
         """
         self._structure_func.register_func_list([(check_func, func)])
 
     def register_structure_hook_factory(
-        self,
-        predicate: Callable[[Any], bool],
-        factory: Callable[[Any], Callable[[Any, Any], Any]],
+        self, predicate: PredicateFn, factory: StructureFnFactory
     ) -> None:
         """
         Register a hook factory for a given predicate.

mergify bot pushed a commit to aws/jsii that referenced this issue Oct 3, 2022
…3 in /packages/@jsii/python-runtime (#3785)

Updates the requirements on [cattrs](https://github.com/python-attrs/cattrs) to permit the latest version.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/python-attrs/cattrs/blob/main/HISTORY.rst">cattrs's changelog</a>.</em></p>
<blockquote>
<h2>22.2.0 (2022-10-03)</h2>
<ul>
<li><em>Potentially breaking</em>: <code>cattrs.Converter</code> has been renamed to <code>cattrs.BaseConverter</code>, and <code>cattrs.GenConverter</code> to <code>cattrs.Converter</code>.
The <code>GenConverter</code> name is still available for backwards compatibility, but is deprecated.
If you were depending on functionality specific to the old <code>Converter</code>, change your import to <code>from cattrs import BaseConverter</code>.</li>
<li><code>NewTypes &lt;https://docs.python.org/3/library/typing.html#newtype&gt;</code>_ are now supported by the <code>cattrs.Converter</code>.
(<code>[#255](python-attrs/cattrs#255) &lt;https://github.com/python-attrs/cattrs/pull/255&gt;</code><em>, <code>[#94](python-attrs/cattrs#94) &lt;https://github.com/python-attrs/cattrs/issues/94&gt;</code></em>, <code>[#297](python-attrs/cattrs#297) &lt;https://github.com/python-attrs/cattrs/issues/297&gt;</code>_)</li>
<li><code>cattrs.Converter</code> and <code>cattrs.BaseConverter</code> can now copy themselves using the <code>copy</code> method.
(<code>[#284](python-attrs/cattrs#284) &lt;https://github.com/python-attrs/cattrs/pull/284&gt;</code>_)</li>
<li>Python 3.11 support.</li>
<li>cattrs now supports un/structuring <code>kw_only</code> fields on attrs classes into/from dictionaries.
(<code>[#247](python-attrs/cattrs#247) &lt;https://github.com/python-attrs/cattrs/pull/247&gt;</code>_)</li>
<li>PyPy support (and tests, using a minimal Hypothesis profile) restored.
(<code>[#253](python-attrs/cattrs#253) &lt;https://github.com/python-attrs/cattrs/issues/253&gt;</code>_)</li>
<li>Fix propagating the <code>detailed_validation</code> flag to mapping and counter structuring generators.</li>
<li>Fix <code>typing.Set</code> applying too broadly when used with the <code>GenConverter.unstruct_collection_overrides</code> parameter on Python versions below 3.9. Switch to <code>typing.AbstractSet</code> on those versions to restore the old behavior.
(<code>[#264](python-attrs/cattrs#264) &lt;https://github.com/python-attrs/cattrs/issues/264&gt;</code>_)</li>
<li>Uncap the required Python version, to avoid problems detailed in <a href="https://iscinumpy.dev/post/bound-version-constraints/#pinning-the-python-version-is-special">https://iscinumpy.dev/post/bound-version-constraints/#pinning-the-python-version-is-special</a>
(<code>[#275](python-attrs/cattrs#275) &lt;https://github.com/python-attrs/cattrs/issues/275&gt;</code>_)</li>
<li>Fix <code>Converter.register_structure_hook_factory</code> and <code>cattrs.gen.make_dict_unstructure_fn</code> type annotations.
(<code>[#281](python-attrs/cattrs#281) &lt;https://github.com/python-attrs/cattrs/issues/281&gt;</code>_)</li>
<li>Expose all error classes in the <code>cattr.errors</code> namespace. Note that it is deprecated, just use <code>cattrs.errors</code>.
(<code>[#252](python-attrs/cattrs#252) &lt;https://github.com/python-attrs/cattrs/issues/252&gt;</code>_)</li>
<li>Fix generating structuring functions for types with quotes in the name.
(<code>[#291](python-attrs/cattrs#291) &lt;https://github.com/python-attrs/cattrs/issues/291&gt;</code>_ <code>[#277](python-attrs/cattrs#277) &lt;https://github.com/python-attrs/cattrs/issues/277&gt;</code>_)</li>
<li>Fix usage of notes for the final version of <code>PEP 678 &lt;https://peps.python.org/pep-0678/&gt;</code><em>, supported since <code>exceptiongroup&gt;=1.0.0rc4</code>.
(<code>[#303](python-attrs/cattrs#303) &lt;303 &lt;https://github.com/python-attrs/cattrs/pull/303&gt;</code></em>)</li>
</ul>
<h2>22.1.0 (2022-04-03)</h2>
<ul>
<li>cattrs now uses the CalVer versioning convention.</li>
<li>cattrs now has a detailed validation mode, which is enabled by default. Learn more <code>here &lt;https://cattrs.readthedocs.io/en/latest/validation.html&gt;</code>_.
The old behavior can be restored by creating the converter with <code>detailed_validation=False</code>.</li>
<li><code>attrs</code> and dataclass structuring is now ~25% faster.</li>
<li>Fix an issue structuring bare <code>typing.List</code> s on Pythons lower than 3.9.
(<code>[#209](python-attrs/cattrs#209) &lt;https://github.com/python-attrs/cattrs/issues/209&gt;</code>_)</li>
<li>Fix structuring of non-parametrized containers like <code>list/dict/...</code> on Pythons lower than 3.9.
(<code>[#218](python-attrs/cattrs#218) &lt;https://github.com/python-attrs/cattrs/issues/218&gt;</code>_)</li>
<li>Fix structuring bare <code>typing.Tuple</code> on Pythons lower than 3.9.
(<code>[#218](python-attrs/cattrs#218) &lt;https://github.com/python-attrs/cattrs/issues/218&gt;</code>_)</li>
<li>Fix a wrong <code>AttributeError</code> of an missing <code>__parameters__</code> attribute. This could happen
when inheriting certain generic classes – for example <code>typing.*</code> classes are affected.
(<code>[#217](python-attrs/cattrs#217) &lt;https://github.com/python-attrs/cattrs/issues/217&gt;</code>_)</li>
<li>Fix structuring of <code>enum.Enum</code> instances in <code>typing.Literal</code> types.
(<code>[#231](python-attrs/cattrs#231) &lt;https://github.com/python-attrs/cattrs/pull/231&gt;</code>_)</li>
<li>Fix unstructuring all tuples - unannotated, variable-length, homogenous and heterogenous - to <code>list</code>.
(<code>[#226](python-attrs/cattrs#226) &lt;https://github.com/python-attrs/cattrs/issues/226&gt;</code>_)</li>
<li>For <code>forbid_extra_keys</code> raise custom <code>ForbiddenExtraKeyError</code> instead of generic <code>Exception</code>.
(<code>[#225](python-attrs/cattrs#225) &lt;https://github.com/python-attrs/cattrs/pull/225&gt;</code>_)</li>
<li>All preconf converters now support <code>loads</code> and <code>dumps</code> directly. See an example <code>here &lt;https://cattrs.readthedocs.io/en/latest/preconf.html&gt;</code>_.</li>
</ul>

</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/python-attrs/cattrs/commit/405f0291b958ae9eb45ee38febeb91fb65dd644f"><code>405f029</code></a> v22.2.0</li>
<li><a href="https://github.com/python-attrs/cattrs/commit/89de04f57aa774d6abfb0ae62517dc8a8064e3c2"><code>89de04f</code></a> Fix some mor</li>
<li><a href="https://github.com/python-attrs/cattrs/commit/0abbf271461babca203862f3581c20743f6118e0"><code>0abbf27</code></a> Fix tests</li>
<li><a href="https://github.com/python-attrs/cattrs/commit/3b750439aec826a8fd20976ca113f30a27e75408"><code>3b75043</code></a> <strong>notes</strong> is list[str]</li>
<li><a href="https://github.com/python-attrs/cattrs/commit/906b95cfef4903e2d6247abf0fdd72f7da21617a"><code>906b95c</code></a> Reorder HISTORY</li>
<li><a href="https://github.com/python-attrs/cattrs/commit/ed7f86a0ccd9adeab895b9afac2dea69fa02bcff"><code>ed7f86a</code></a> Improve NewTypes (<a href="https://github-redirect.dependabot.com/python-attrs/cattrs/issues/310">#310</a>)</li>
<li><a href="https://github.com/python-attrs/cattrs/commit/e7926599ad44e07d8325ae4072626e1a24705542"><code>e792659</code></a> Fix missing imports of preconf converters (<a href="https://github-redirect.dependabot.com/python-attrs/cattrs/issues/309">#309</a>)</li>
<li><a href="https://github.com/python-attrs/cattrs/commit/e425d6378aa8dfc74bbdd9e152365e1b962fd8cf"><code>e425d63</code></a> Reorder HISTORY</li>
<li><a href="https://github.com/python-attrs/cattrs/commit/cc56b2b873852a4e91b16706a39da00755c87759"><code>cc56b2b</code></a> Remove spurious type comment</li>
<li><a href="https://github.com/python-attrs/cattrs/commit/cbd6f29d2c0ebc40805b3ca0d81accfc330eb10c"><code>cbd6f29</code></a> Reformat</li>
<li>Additional commits viewable in <a href="https://github.com/python-attrs/cattrs/compare/v1.8.0...v22.2.0">compare view</a></li>
</ul>
</details>
<br />


Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)


</details>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants