Skip to content

Commit

Permalink
Create a partial match object proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
Milan Falešník committed Aug 31, 2017
1 parent 1f8fcb9 commit f2e0528
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
28 changes: 28 additions & 0 deletions src/widgetastic/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,3 +545,31 @@ def crop_string_middle(s, length=32, cropper='...'):
return s
half = (length - len(cropper)) / 2
return s[:half] + cropper + s[-half - 1:]


class partial_match(object): # noqa
"""Use this to wrap values to be selected using partial matching in various objects.
It proxies all ``get`` operations to the underlying ``item``.
It also proxies ``dir`` so you get the exactly same result of :py:func:`dir` as if you did it
on the wrapped object.
"""
def __init__(self, item):
self.item = item

def __dir__(self):
return dir(self.item)

def __getattr__(self, attr):
return getattr(self.item, attr)

def __setattr__(self, attr, value):
if attr == 'item':
super(partial_match, self).__setattr__(attr, value)
else:
setattr(self.item, attr, value)

def __repr__(self):
return 'partial_match({!r})'.format(self.item)
13 changes: 12 additions & 1 deletion testing/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import pytest

from widgetastic.utils import nested_getattr
from widgetastic.utils import nested_getattr, partial_match


def test_nested_getattr_wrong_type():
Expand Down Expand Up @@ -30,3 +30,14 @@ class bar(object): # noqa

assert nested_getattr(Obj, 'foo.bar.lol') == 'heh'
assert nested_getattr(Obj, ['foo', 'bar', 'lol']) == 'heh'


def test_partial_match_wrapping():
value = ' foobar '
wrapped = partial_match(value)

assert dir(wrapped) == dir(value)

assert wrapped.item is value

assert wrapped.strip() == value.strip()

0 comments on commit f2e0528

Please sign in to comment.