- Notifications
You must be signed in to change notification settings - Fork 26
Record: make field ordering deterministic, add test#199
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
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
1386433
Record: make field ordering deterministic
matthiasdiener 2e75f46
add set conversion to __setstate__
matthiasdiener 35c3685
remove duplicate/unnecessary definitions
matthiasdiener f6c762a
add warning
matthiasdiener 0b43c94
fix register_fields
matthiasdiener 6e3bb4f
improve tests
matthiasdiener 0608e1e
add pickle test
matthiasdiener 73327b4
restore __slots__ in Record, add to test
matthiasdiener d091bac
better warning
matthiasdiener 0a508c4
add type annotations
matthiasdiener File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -37,7 +37,7 @@ | ||
| from sys import intern | ||
| from typing import ( | ||
| Any, Callable, ClassVar, Dict, Generic, Hashable, Iterable, Iterator, List, | ||
| Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union) | ||
| Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, cast) | ||
| try: | ||
| @@ -411,9 +411,16 @@ class RecordWithoutPickling: | ||
| """ | ||
| __slots__: ClassVar[List[str]] = [] | ||
| fields: ClassVar[Set[str]] | ||
| def __init__(self, valuedict=None, exclude=None, **kwargs): | ||
| # A dict, not a set, to maintain a deterministic iteration order | ||
| fields: ClassVar[Dict[str, None]] | ||
| def __init__(self, valuedict: Optional[Mapping[str, Any]] = None, | ||
| exclude: Optional[Iterable[str]] = None, **kwargs: Any) -> None: | ||
| from warnings import warn | ||
| warn(f"{self.__class__.__bases__[0]} is deprecated and will be " | ||
| "removed in 2025. Use dataclasses instead.") | ||
| assert self.__class__ is not Record | ||
| if exclude is None: | ||
| @@ -422,17 +429,20 @@ def __init__(self, valuedict=None, exclude=None, **kwargs): | ||
| try: | ||
| fields = self.__class__.fields | ||
| except AttributeError: | ||
| self.__class__.fields = fields = set() | ||
| self.__class__.fields = fields = {} | ||
| if isinstance(fields, set): | ||
| self.__class__.fields = fields = dict.fromkeys(sorted(fields)) | ||
| if valuedict is not None: | ||
| kwargs.update(valuedict) | ||
| for key, value in kwargs.items(): | ||
| if key not in exclude: | ||
| fields.add(key) | ||
| fields[key] = None | ||
| setattr(self, key, value) | ||
| def get_copy_kwargs(self, **kwargs): | ||
| def get_copy_kwargs(self, **kwargs: Any) -> Dict[str, Any]: | ||
| for f in self.__class__.fields: | ||
| if f not in kwargs: | ||
| try: | ||
| @@ -441,25 +451,25 @@ def get_copy_kwargs(self, **kwargs): | ||
| pass | ||
| return kwargs | ||
| def copy(self, **kwargs): | ||
| def copy(self, **kwargs: Any) -> "RecordWithoutPickling": | ||
| return self.__class__(**self.get_copy_kwargs(**kwargs)) | ||
| def __repr__(self): | ||
| def __repr__(self) -> str: | ||
| return "{}({})".format( | ||
| self.__class__.__name__, | ||
| ", ".join(f"{fld}={getattr(self, fld)!r}" | ||
| for fld in self.__class__.fields | ||
| if hasattr(self, fld))) | ||
| def register_fields(self, new_fields): | ||
| def register_fields(self, new_fields: Iterable[str]) -> None: | ||
| try: | ||
| fields = self.__class__.fields | ||
| except AttributeError: | ||
| self.__class__.fields = fields = set() | ||
| self.__class__.fields = fields = {} | ||
| fields.update(new_fields) | ||
| fields.update(dict.fromkeys(sorted(new_fields))) | ||
| def __getattr__(self, name): | ||
| def __getattr__(self, name: str) -> Any: | ||
| # This method is implemented to avoid pylint 'no-member' errors for | ||
| # attribute access. | ||
| raise AttributeError( | ||
| @@ -470,46 +480,46 @@ def __getattr__(self, name): | ||
| class Record(RecordWithoutPickling): | ||
| __slots__: ClassVar[List[str]] = [] | ||
inducer marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| def __getstate__(self): | ||
| def __getstate__(self) -> Dict[str, Any]: | ||
| return { | ||
| key: getattr(self, key) | ||
| for key in self.__class__.fields | ||
| if hasattr(self, key)} | ||
| def __setstate__(self, valuedict): | ||
| def __setstate__(self, valuedict: Mapping[str, Any]) -> None: | ||
| try: | ||
| fields = self.__class__.fields | ||
| except AttributeError: | ||
| self.__class__.fields = fields = set() | ||
| self.__class__.fields = fields = {} | ||
| if isinstance(fields, set): | ||
| self.__class__.fields = fields = dict.fromkeys(sorted(fields)) | ||
| for key, value in valuedict.items(): | ||
| fields.add(key) | ||
| fields[key] = None | ||
| setattr(self, key, value) | ||
| def __eq__(self, other): | ||
| def __eq__(self, other: Any) -> bool: | ||
| if self is other: | ||
| return True | ||
| return (self.__class__ == other.__class__ | ||
| and self.__getstate__() == other.__getstate__()) | ||
| def __ne__(self, other): | ||
| return not self.__eq__(other) | ||
| class ImmutableRecordWithoutPickling(RecordWithoutPickling): | ||
| """Hashable record. Does not explicitly enforce immutability.""" | ||
| def __init__(self, *args, **kwargs): | ||
| def __init__(self, *args: Any, **kwargs: Any) -> None: | ||
| RecordWithoutPickling.__init__(self, *args, **kwargs) | ||
| self._cached_hash = None | ||
| self._cached_hash: Optional[int] = None | ||
| def __hash__(self): | ||
| def __hash__(self) -> int: | ||
| # This attribute may vanish during pickling. | ||
| if getattr(self, "_cached_hash", None) is None: | ||
| self._cached_hash = hash( | ||
| (type(self),) + tuple(getattr(self, field) | ||
| for field in self.__class__.fields)) | ||
| return self._cached_hash | ||
| return cast(int, self._cached_hash) | ||
| class ImmutableRecord(ImmutableRecordWithoutPickling, Record): | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.