-
Notifications
You must be signed in to change notification settings - Fork 24
feat: __dict__ major simplification #477
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
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
de9ebf0
feat: __dict__ (WIP)
henryiii e7e3f5c
fix: python 2 support
henryiii 7398693
feat: support all other axes types
henryiii 22f63f1
fix: test __dict__ and fix bug with categories missing slots
henryiii f1a09f3
fix: force subclasses to have __slots__
henryiii 80aa9f2
refactor!: real __dict__ instead of facade!
henryiii 4b2a5e1
refactor: minor cleanup
henryiii File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
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
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
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 |
---|---|---|
|
@@ -30,35 +30,52 @@ def _isstr(value): | |
# Contains common methods and properties to all axes | ||
@set_module("boost_histogram.axis") | ||
class Axis(object): | ||
__slots__ = ("_ax",) | ||
__slots__ = ("_ax", "__dict__") | ||
|
||
def __copy__(self): | ||
other = self.__class__.__new__(self.__class__) | ||
other._ax = copy.copy(self._ax) | ||
return other | ||
def __setattr__(self, attr, value): | ||
if attr == "__dict__": | ||
self._ax.metadata = value | ||
object.__setattr__(self, attr, value) | ||
|
||
def __getattr__(self, item): | ||
if item == "_ax": | ||
return Axis.__dict__[item].__get__(self) | ||
elif item in self._ax.metadata: | ||
return self._ax.metadata[item] | ||
elif item == "metadata": | ||
def __getattr__(self, attr): | ||
if attr == "metadata": | ||
return None | ||
else: | ||
msg = "'{}' object has no attribute '{}' in {}".format( | ||
type(self).__name__, item, set(self._ax.metadata) | ||
raise AttributeError( | ||
"object {0} has not attribute {1}".format(self.__class__.__name__, attr) | ||
) | ||
|
||
def __init__(self, ax, metadata, __dict__): | ||
""" | ||
ax: the C++ object | ||
metadata: the metadata keyword contents | ||
__dict__: the __dict__ keyword contents | ||
""" | ||
|
||
self._ax = ax | ||
|
||
if __dict__ is not None and metadata is not None: | ||
raise KeyError( | ||
"Cannot provide metadata by keyword and __dict__, use __dict__ only" | ||
) | ||
raise AttributeError(msg) | ||
elif __dict__ is not None: | ||
self._ax.metadata = __dict__ | ||
elif metadata is not None: | ||
self._ax.metadata["metadata"] = metadata | ||
|
||
def __setattr__(self, item, value): | ||
if item == "_ax": | ||
Axis.__dict__[item].__set__(self, value) | ||
else: | ||
self._ax.metadata[item] = value | ||
self.__dict__ = self._ax.metadata | ||
|
||
def __setstate__(self, state): | ||
self._ax = state["_ax"] | ||
self.__dict__ = self._ax.metadata | ||
|
||
def __getstate__(self): | ||
return {"_ax": self._ax} | ||
|
||
def __dir__(self): | ||
metadata = list(self._ax.metadata) | ||
return sorted(dir(type(self)) + metadata) | ||
def __copy__(self): | ||
other = self.__class__.__new__(self.__class__) | ||
other._ax = copy.copy(self._ax) | ||
other.__dict__ = other._ax.metadata | ||
return other | ||
|
||
def index(self, value): | ||
""" | ||
|
@@ -100,6 +117,7 @@ def __ne__(self, other): | |
def _convert_cpp(cls, cpp_object): | ||
nice_ax = cls.__new__(cls) | ||
nice_ax._ax = cpp_object | ||
nice_ax.__dict__ = cpp_object.metadata | ||
return nice_ax | ||
|
||
def __len__(self): | ||
|
@@ -230,7 +248,7 @@ class Regular(Axis): | |
__slots__ = () | ||
|
||
@inject_signature( | ||
"self, bins, start, stop, *, metadata=None, underflow=True, overflow=True, growth=False, circular=False, transform=None" | ||
"self, bins, start, stop, *, metadata=None, underflow=True, overflow=True, growth=False, circular=False, transform=None, __dict__=None" | ||
) | ||
def __init__(self, bins, start, stop, **kwargs): | ||
""" | ||
|
@@ -258,11 +276,14 @@ def __init__(self, bins, start, stop, **kwargs): | |
Filling wraps around. | ||
transform : Optional[AxisTransform] = None | ||
Transform the regular bins (Log, Sqrt, and Pow(v)) | ||
__dict__: Optional[Dict[str, Any]] = None | ||
The full metadata dictionary | ||
""" | ||
|
||
with KWArgs(kwargs) as k: | ||
metadata = k.optional("metadata") | ||
transform = k.optional("transform") | ||
__dict__ = k.optional("__dict__") | ||
options = k.options( | ||
underflow=True, overflow=True, growth=False, circular=False | ||
) | ||
|
@@ -277,29 +298,29 @@ def __init__(self, bins, start, stop, **kwargs): | |
): | ||
raise TypeError("You must pass an instance, use {}()".format(transform)) | ||
|
||
self._ax = transform._produce(bins, start, stop) | ||
ax = transform._produce(bins, start, stop) | ||
|
||
elif options == {"growth", "underflow", "overflow"}: | ||
self._ax = ca.regular_uoflow_growth(bins, start, stop) | ||
ax = ca.regular_uoflow_growth(bins, start, stop) | ||
elif options == {"underflow", "overflow"}: | ||
self._ax = ca.regular_uoflow(bins, start, stop) | ||
ax = ca.regular_uoflow(bins, start, stop) | ||
elif options == {"underflow"}: | ||
self._ax = ca.regular_uflow(bins, start, stop) | ||
ax = ca.regular_uflow(bins, start, stop) | ||
elif options == {"overflow"}: | ||
self._ax = ca.regular_oflow(bins, start, stop) | ||
ax = ca.regular_oflow(bins, start, stop) | ||
elif options == {"circular", "underflow", "overflow"} or options == { | ||
"circular", | ||
"overflow", | ||
}: | ||
# growth=True, underflow=False is also correct | ||
self._ax = ca.regular_circular(bins, start, stop) | ||
ax = ca.regular_circular(bins, start, stop) | ||
|
||
elif options == set(): | ||
self._ax = ca.regular_none(bins, start, stop) | ||
ax = ca.regular_none(bins, start, stop) | ||
else: | ||
raise KeyError("Unsupported collection of options") | ||
|
||
self.metadata = metadata | ||
super(Regular, self).__init__(ax, metadata, __dict__) | ||
|
||
def _repr_args(self): | ||
"Return inner part of signature for use in repr" | ||
|
@@ -339,7 +360,7 @@ class Variable(Axis): | |
__slots__ = () | ||
|
||
@inject_signature( | ||
"self, edges, *, metadata=None, underflow=True, overflow=True, growth=False" | ||
"self, edges, *, metadata=None, underflow=True, overflow=True, growth=False, __dict__=None" | ||
) | ||
def __init__(self, edges, **kwargs): | ||
""" | ||
|
@@ -361,33 +382,37 @@ def __init__(self, edges, **kwargs): | |
growth : bool = False | ||
Allow the axis to grow if a value is encountered out of range. | ||
Be careful, the axis will grow as large as needed. | ||
__dict__: Optional[Dict[str, Any]] = None | ||
The full metadata dictionary | ||
""" | ||
|
||
with KWArgs(kwargs) as k: | ||
metadata = k.optional("metadata") | ||
__dict__ = k.optional("__dict__") | ||
options = k.options( | ||
underflow=True, overflow=True, circular=False, growth=False | ||
) | ||
|
||
if options == {"growth", "underflow", "overflow"}: | ||
self._ax = ca.variable_uoflow_growth(edges) | ||
ax = ca.variable_uoflow_growth(edges) | ||
elif options == {"underflow", "overflow"}: | ||
self._ax = ca.variable_uoflow(edges) | ||
ax = ca.variable_uoflow(edges) | ||
elif options == {"underflow"}: | ||
self._ax = ca.variable_uflow(edges) | ||
ax = ca.variable_uflow(edges) | ||
elif options == {"overflow"}: | ||
self._ax = ca.variable_oflow(edges) | ||
ax = ca.variable_oflow(edges) | ||
elif options == {"circular", "underflow", "overflow",} or options == { | ||
"circular", | ||
"overflow", | ||
}: | ||
# growth=True, underflow=False is also correct | ||
self._ax = ca.variable_circular(edges) | ||
ax = ca.variable_circular(edges) | ||
elif options == set(): | ||
self._ax = ca.variable_none(edges) | ||
ax = ca.variable_none(edges) | ||
else: | ||
raise KeyError("Unsupported collection of options") | ||
|
||
self.metadata = metadata | ||
super(Variable, self).__init__(ax, metadata, __dict__) | ||
|
||
def _repr_args(self): | ||
"Return inner part of signature for use in repr" | ||
|
@@ -414,7 +439,7 @@ class Integer(Axis): | |
__slots__ = () | ||
|
||
@inject_signature( | ||
"self, start, stop, *, metadata=None, underflow=True, overflow=True, growth=False" | ||
"self, start, stop, *, metadata=None, underflow=True, overflow=True, growth=False, __dict__=None" | ||
) | ||
def __init__(self, start, stop, **kwargs): | ||
""" | ||
|
@@ -437,31 +462,35 @@ def __init__(self, start, stop, **kwargs): | |
growth : bool = False | ||
Allow the axis to grow if a value is encountered out of range. | ||
Be careful, the axis will grow as large as needed. | ||
__dict__: Optional[Dict[str, Any]] = None | ||
The full metadata dictionary | ||
""" | ||
|
||
with KWArgs(kwargs) as k: | ||
metadata = k.optional("metadata") | ||
__dict__ = k.optional("__dict__") | ||
options = k.options( | ||
underflow=True, overflow=True, circular=False, growth=False | ||
) | ||
|
||
# underflow and overflow settings are ignored, integers are always | ||
# finite and thus cannot end up in a flow bin when growth is on | ||
if "growth" in options and "circular" not in options: | ||
self._ax = ca.integer_growth(start, stop) | ||
ax = ca.integer_growth(start, stop) | ||
elif options == {"underflow", "overflow"}: | ||
self._ax = ca.integer_uoflow(start, stop) | ||
ax = ca.integer_uoflow(start, stop) | ||
elif options == {"underflow"}: | ||
self._ax = ca.integer_uflow(start, stop) | ||
ax = ca.integer_uflow(start, stop) | ||
elif options == {"overflow"}: | ||
self._ax = ca.integer_oflow(start, stop) | ||
ax = ca.integer_oflow(start, stop) | ||
elif "circular" in options and "growth" not in options: | ||
self._ax = ca.integer_circular(start, stop) | ||
ax = ca.integer_circular(start, stop) | ||
elif options == set(): | ||
self._ax = ca.integer_none(start, stop) | ||
ax = ca.integer_none(start, stop) | ||
else: | ||
raise KeyError("Unsupported collection of options") | ||
|
||
self.metadata = metadata | ||
super(Integer, self).__init__(ax, metadata, __dict__) | ||
|
||
def _repr_args(self): | ||
"Return inner part of signature for use in repr" | ||
|
@@ -495,7 +524,9 @@ def _repr_kwargs(self): | |
@set_module("boost_histogram.axis") | ||
@register({ca.category_str_growth, ca.category_str}) | ||
class StrCategory(BaseCategory): | ||
@inject_signature("self, categories, *, metadata=None, growth=False") | ||
__slots__ = () | ||
|
||
@inject_signature("self, categories, *, metadata=None, growth=False, __dict__=None") | ||
def __init__(self, categories, **kwargs): | ||
""" | ||
Make a category axis with strings; items will | ||
|
@@ -512,22 +543,26 @@ def __init__(self, categories, **kwargs): | |
growth : bool = False | ||
Allow the axis to grow if a value is encountered out of range. | ||
Be careful, the axis will grow as large as needed. | ||
__dict__: Optional[Dict[str, Any]] = None | ||
The full metadata dictionary | ||
""" | ||
|
||
with KWArgs(kwargs) as k: | ||
metadata = k.optional("metadata") | ||
__dict__ = k.optional("__dict__") | ||
options = k.options(growth=False) | ||
|
||
# henryiii: We currently expand "abc" to "a", "b", "c" - some | ||
# Python interfaces protect against that | ||
|
||
if options == {"growth"}: | ||
self._ax = ca.category_str_growth(tuple(categories)) | ||
ax = ca.category_str_growth(tuple(categories)) | ||
elif options == set(): | ||
self._ax = ca.category_str(tuple(categories)) | ||
ax = ca.category_str(tuple(categories)) | ||
else: | ||
raise KeyError("Unsupported collection of options") | ||
|
||
self.metadata = metadata | ||
super(StrCategory, self).__init__(ax, metadata, __dict__) | ||
|
||
def index(self, value): | ||
""" | ||
|
@@ -553,7 +588,9 @@ def _repr_args(self): | |
@set_module("boost_histogram.axis") | ||
@register({ca.category_int, ca.category_int_growth}) | ||
class IntCategory(BaseCategory): | ||
@inject_signature("self, categories, *, metadata=None, growth=False") | ||
__slots__ = () | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This was a bug (missing |
||
|
||
@inject_signature("self, categories, *, metadata=None, growth=False, __dict__=None") | ||
def __init__(self, categories, **kwargs): | ||
""" | ||
Make a category axis with ints; items will | ||
|
@@ -570,19 +607,23 @@ def __init__(self, categories, **kwargs): | |
growth : bool = False | ||
Allow the axis to grow if a value is encountered out of range. | ||
Be careful, the axis will grow as large as needed. | ||
__dict__: Optional[Dict[str, Any]] = None | ||
The full metadata dictionary | ||
""" | ||
|
||
with KWArgs(kwargs) as k: | ||
metadata = k.optional("metadata") | ||
__dict__ = k.optional("__dict__") | ||
options = k.options(growth=False) | ||
|
||
if options == {"growth"}: | ||
self._ax = ca.category_int_growth(tuple(categories)) | ||
ax = ca.category_int_growth(tuple(categories)) | ||
elif options == set(): | ||
self._ax = ca.category_int(tuple(categories)) | ||
ax = ca.category_int(tuple(categories)) | ||
else: | ||
raise KeyError("Unsupported collection of options") | ||
|
||
self.metadata = metadata | ||
super(IntCategory, self).__init__(ax, metadata, __dict__) | ||
|
||
def _repr_args(self): | ||
"Return inner part of signature for use in repr" | ||
|
@@ -597,7 +638,7 @@ def _repr_args(self): | |
class Boolean(Axis): | ||
__slots__ = () | ||
|
||
@inject_signature("self, *, metadata=None") | ||
@inject_signature("self, *, metadata=None, __dict__=None") | ||
def __init__(self, **kwargs): | ||
""" | ||
Make an axis for boolean values. | ||
|
@@ -606,12 +647,17 @@ def __init__(self, **kwargs): | |
---------- | ||
metadata : object | ||
Any Python object to attach to the axis, like a label. | ||
__dict__: Optional[Dict[str, Any]] = None | ||
The full metadata dictionary | ||
""" | ||
|
||
with KWArgs(kwargs) as k: | ||
metadata = k.optional("metadata") | ||
__dict__ = k.optional("__dict__") | ||
|
||
ax = ca.boolean() | ||
|
||
self._ax = ca.boolean() | ||
self.metadata = metadata | ||
super(Boolean, self).__init__(ax, metadata, __dict__) | ||
|
||
def _repr_args(self): | ||
"Return inner part of signature for use in repr" | ||
|
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This sort of thing is no longer needed! :)