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

Refactor swizzle function and bump version number #2

Merged
merged 4 commits into from
Aug 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ print(xyz.yzx) # Output: (2, 3, 1)
```


### Sequential matching
Attributes are matched from left to right, starting with the longest substring match.
### Sequential matching
Attributes are matched from left to right, starting with the longest substring match.
```python
import swizzle

Expand All @@ -103,5 +103,4 @@ print(Test.xyzx) # Output: (7, 1)
```

## To Do
- [ ] Add support for module-level swizzling
- [ ] Swizzle for method args (swizzle+partial)
136 changes: 84 additions & 52 deletions swizzle/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,79 +2,111 @@
import sys
import types

__version__ = "0.1.4"
__version__ = "1.0.0"
MISSING = object()

def _split(s, sep):
if sep == '':
return list(s)

# Helper function to split a string based on a separator
def split_string(string, separator):
if separator == '':
return list(string)
else:
return s.split(sep)

def _swizzle(func, sep = None):
def _getattr(obj, name, default=object()):
try:
return func(obj, name)
except AttributeError:
return default

@wraps(func)
def _swizzle_attributes(obj, name):
"""Find attributes of an object that match substrings of a given name."""
try:
return func(obj, name)
except AttributeError:
pass
if sep is not None:
names = _split(name, sep)
found_attributes = [func(obj, n) for n in names]
return string.split(separator)

# Helper function to collect attribute retrieval functions from a class or meta-class
def collect_attribute_functions(cls):
funcs = []
if hasattr(cls, '__getattribute__'):
funcs.append(cls.__getattribute__)
if hasattr(cls, '__getattr__'):
funcs.append(cls.__getattr__)
if not funcs:
raise AttributeError("No __getattr__ or __getattribute__ found on the class or meta-class")
return funcs

# Function to combine multiple attribute retrieval functions
def swizzle_attributes_retriever(attribute_funcs, separator=None):
def retrieve_attribute(obj, attr_name):
for func in attribute_funcs:
try:
return func(obj, attr_name)
except AttributeError:
continue
return MISSING

@wraps(attribute_funcs[-1])
def retrieve_swizzled_attributes(obj, attr_name):
# Attempt to find an exact attribute match
attribute = retrieve_attribute(obj, attr_name)
if attribute is not MISSING:
return attribute

matched_attributes = []

# If a separator is provided, split the name accordingly
if separator is not None:
attr_parts = split_string(attr_name, separator)
for part in attr_parts:
attribute = retrieve_attribute(obj, part)
if attribute is not MISSING:
matched_attributes.append(attribute)
else:
found_attributes = []
sentinel = object()
# No separator provided, attempt to match substrings
i = 0
while i < len(name):
while i < len(attr_name):
match_found = False
for j in range(len(name), i, -1):
substr = name[i:j]
attr = _getattr(obj, substr, sentinel)
if attr is not sentinel:
found_attributes.append(attr)
for j in range(len(attr_name), i, -1):
substring = attr_name[i:j]
attribute = retrieve_attribute(obj, substring)
if attribute is not MISSING:
matched_attributes.append(attribute)
i = j # Move index to end of the matched substring
match_found = True
break
if not match_found:
raise AttributeError(f"No matching attribute found for substring: {name[i:]}")
return tuple(found_attributes)
return _swizzle_attributes

def swizzle(cls=None, meta = False, sep = None):
def decorator(cls):
# Decorate the class's __getattr__ or __getattribute__
cls_fn = cls.__getattr__ if hasattr(cls, '__getattr__') else cls.__getattribute__
setattr(cls, cls_fn.__name__, _swizzle(cls_fn, sep))

# Handle the meta class
if meta:
raise AttributeError(f"No matching attribute found for substring: {attr_name[i:]}")

return tuple(matched_attributes)

return retrieve_swizzled_attributes

# Decorator function to enable swizzling for a class
def swizzle(cls=None, use_meta=False, separator=None):
def class_decorator(cls):
# Collect attribute retrieval functions from the class
attribute_funcs = collect_attribute_functions(cls)

# Apply the swizzling to the class's attribute retrieval
setattr(cls, attribute_funcs[-1].__name__, swizzle_attributes_retriever(attribute_funcs, separator))

# Handle meta-class swizzling if requested
if use_meta:
meta_cls = type(cls)
if meta_cls == type:
class SwizzleType(meta_cls): pass
meta_cls = SwizzleType
class SwizzledMetaType(meta_cls):
pass
meta_cls = SwizzledMetaType
cls = meta_cls(cls.__name__, cls.__bases__, dict(cls.__dict__))
meta_fn = meta_cls.__getattr__ if hasattr(meta_cls, '__getattr__') else meta_cls.__getattribute__
setattr(meta_cls, meta_fn.__name__, _swizzle(meta_fn, sep))
meta_cls = SwizzledMetaType
cls = meta_cls(cls.__name__, cls.__bases__, dict(cls.__dict__))

meta_funcs = collect_attribute_functions(meta_cls)
setattr(meta_cls, meta_funcs[-1].__name__, swizzle_attributes_retriever(meta_funcs, separator))

return cls

if cls is None:
return decorator
return class_decorator
else:
return decorator(cls)

return class_decorator(cls)


class Swizzle(types.ModuleType):
def __init__(self):
types.ModuleType.__init__(self, __name__)
self.__dict__.update(sys.modules[__name__].__dict__)

def __call__(self, cls=None, meta=False, sep = None):
return swizzle(cls, meta, sep)

sys.modules[__name__] = Swizzle()

Loading