Skip to content

Commit

Permalink
Merge pull request #125 from swinman/master
Browse files Browse the repository at this point in the history
make find and find_descriptor easier to understand
  • Loading branch information
walac committed Jan 25, 2016
2 parents c1544b0 + d03669c commit 69662f7
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 31 deletions.
7 changes: 6 additions & 1 deletion usb/_interop.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@
except (ImportError, AttributeError):
_reduce = reduce

# all, introduced in Python 2.5
try:
_all = all
except NameError:
_all = lambda iter_ : _reduce( lambda x, y: x and y, iter_, True )

# we only have the builtin set type since 2.5 version
try:
_set = set
Expand Down Expand Up @@ -90,4 +96,3 @@ def as_array(data=None):
a = array.array('B')
a.fromstring(data) # deprecated since 3.2
return a

20 changes: 5 additions & 15 deletions usb/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1242,19 +1242,11 @@ def is_printer(dev):
Backends are explained in the usb.backend module.
"""

def device_iter(k, v):
def device_iter(**kwargs):
for dev in backend.enumerate_devices():
d = Device(dev, backend)
if _interop._reduce(
lambda a, b: a and b,
map(
operator.eq,
v,
map(lambda i: getattr(d, i), k)
),
True
) and (custom_match is None or custom_match(d)):
tests = (val == getattr(d, key) for key, val in kwargs.items())
if _interop._all(tests) and (custom_match is None or custom_match(d)):
yield d

if backend is None:
Expand All @@ -1270,13 +1262,11 @@ def device_iter(k, v):
else:
raise NoBackendError('No backend available')

k, v = args.keys(), args.values()

if find_all:
return device_iter(k, v)
return device_iter(**args)
else:
try:
return _interop._next(device_iter(k, v))
return _interop._next(device_iter(**args))
except StopIteration:
return None

Expand Down
20 changes: 5 additions & 15 deletions usb/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,27 +177,17 @@ def find_descriptor(desc, find_all=False, custom_match=None, **args):
find_descriptor function also accepts the find_all parameter to get
an iterator instead of just one descriptor.
"""
def desc_iter(k, v):
def desc_iter(**kwargs):
for d in desc:
if (custom_match is None or custom_match(d)) and \
_interop._reduce(
lambda a, b: a and b,
map(
operator.eq,
v,
map(lambda i: getattr(d, i), k)
),
True
):
tests = (val == getattr(d, key) for key, val in kwargs.items())
if _interop._all(tests) and (custom_match is None or custom_match(d)):
yield d

k, v = args.keys(), args.values()

if find_all:
return desc_iter(k, v)
return desc_iter(**args)
else:
try:
return _interop._next(desc_iter(k, v))
return _interop._next(desc_iter(**args))
except StopIteration:
return None

Expand Down

0 comments on commit 69662f7

Please sign in to comment.