Skip to content

Instantly share code, notes, and snippets.

@svermeulen
Last active September 15, 2021 15:13
Show Gist options
  • Save svermeulen/8a6ad727113a6d07f78332152c1d33b2 to your computer and use it in GitHub Desktop.
Save svermeulen/8a6ad727113a6d07f78332152c1d33b2 to your computer and use it in GitHub Desktop.
from dataclasses import dataclass, is_dataclass
import typeguard
from typing import List
from typeguard import typechecked
@typechecked
def _add_validate_member_types_method(cls:type):
def _validate_member_types(self):
for member_name, member_type in cls.__annotations__.items():
member_value = getattr(self, member_name)
typeguard.check_type(member_name, member_value, member_type)
assert not hasattr(cls, '_validate_member_types')
cls._validate_member_types = _validate_member_types
@typechecked
def _override_set_state_method(cls:type):
old_set_state = getattr(cls, '__setstate__', None)
# Override setstate so that we detect when errors occur during unpickling
def setstate(self, d):
if old_set_state is not None:
old_set_state(self, d)
else:
self.__dict__ = d
self._validate_member_types()
cls.__setstate__ = setstate
@typechecked
def _override_post_init_method(cls:type):
old_post_init = getattr(cls, '__post_init__', None)
# Post init will catch type errors passed when using the generated constructor
def postinit(self):
self._validate_member_types()
if old_post_init is not None:
old_post_init(self)
cls.__post_init__ = postinit
@typechecked
def _override_set_attr_method(cls:type):
old_set_attr = getattr(cls, '__setattr__', None)
MISSING = object()
def setattr(self, name, value):
# Don't type check private members
if not name.startswith("_"):
member_type_map = getattr(cls, '__annotations__', None)
found_member = False
if member_type_map is not None:
expected_type = member_type_map.get(name, MISSING)
if expected_type is not MISSING:
found_member = True
typeguard.check_type(name, value, expected_type)
if not found_member:
raise AttributeError(
f"Type '{self.__class__}' has not declared a member with name '{name}'")
if old_set_attr is not None:
old_set_attr(self, name, value)
else:
self.__dict__[name] = value
cls.__setattr__ = setattr
def _dataclass_typechecked(cls, *args, **kwargs):
assert not is_dataclass(cls), "Not necessary to apply both @dataclass and @dataclass_typechecked"
cls = dataclass(cls, *args, **kwargs)
_add_validate_member_types_method(cls)
_override_set_state_method(cls)
_override_post_init_method(cls)
# Setting frozen to True already does this for us and throws if we try and override it
if not kwargs.get('frozen', False):
_override_set_attr_method(cls)
return cls
def dataclass_typechecked(cls=None, *args, **kwargs):
def wrap(cls):
return _dataclass_typechecked(cls, *args, **kwargs)
# See if we're being called as @dataclass_typechecked or @dataclass_typechecked().
if cls is None:
# We're called with parameters
return wrap
# We're called as @dataclass_typechecked without parameters
return wrap(cls)
MIT License
Copyright (c) 2021 Steven Vermeulen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@chilabot
Copy link

chilabot commented Apr 22, 2021

Had to put 'if member_type != typing.ClassVar' for it to work.

Forward reference to the current class by name doesn't work. Had to use 'cls'.

@dataclass_typechecked
class Elements:
    Data:       typing.ClassVar = typing.Union[str, int, 'cls']
    Struct:     typing.ClassVar = typing.Dict[str, Data]

    VisitFun:   typing.ClassVar = typing.Callable[[str, 'cls'], None]

    elements:   typing.Dict[str, Struct]

@dblock
Copy link

dblock commented Sep 15, 2021

@svermeulen can you please assign a license to this so we can reuse it? Thanks

@svermeulen
Copy link
Author

@dblock Done

@dblock
Copy link

dblock commented Sep 15, 2021

Note for fixing later: inheritance doesn't quite seem to work, child class attributes aren't found.
See agronholm/typeguard#161 for PRing this upstream.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment