Skip to content

Commit

Permalink
Use format instead of %
Browse files Browse the repository at this point in the history
We can't *quite* switch to f-strings yet as that's strictly 3.6 and
above, but we can use format in a manner pretty damned close to what we
eventually want. This commit should make the future migration to
f-strings quite a bit easier
  • Loading branch information
waveform80 committed Mar 19, 2021
1 parent 6730b17 commit 5ea3c6a
Show file tree
Hide file tree
Showing 25 changed files with 372 additions and 234 deletions.
2 changes: 1 addition & 1 deletion docs/examples/button_camera_1.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

def capture():
timestamp = datetime.now().isoformat()
camera.capture('/home/pi/%s.jpg' % timestamp)
camera.capture('/home/pi/{timestamp}.jpg'.format(timestamp=timestamp))

button.when_pressed = capture

Expand Down
2 changes: 1 addition & 1 deletion docs/examples/button_camera_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

def capture():
timestamp = datetime.now().isoformat()
camera.capture('/home/pi/%s.jpg' % timestamp)
camera.capture('/home/pi/{timestamp}.jpg'.format(timestamp=timestamp))

left_button.when_pressed = camera.start_preview
left_button.when_released = camera.stop_preview
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/button_stop_motion.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@
frame = 1
while True:
button.wait_for_press()
camera.capture('/home/pi/frame%03d.jpg' % frame)
camera.capture('/home/pi/frame{frame:03d}.jpg'.format(frame=frame))
frame += 1
22 changes: 12 additions & 10 deletions gpiozero/boards.py
Original file line number Diff line number Diff line change
Expand Up @@ -1315,7 +1315,7 @@ def __init__(self, *, pwm=False, initial_value=False, pin_factory=None):
pins = (4, 15, 13, 21, 25, 8, 5, 10, 16, 17, 27, 26,
24, 9, 12, 6, 20, 19, 14, 18, 11, 7, 23, 22)
for i, pin in enumerate(pins):
pins_dict['led%d' % (i+1)] = pin
pins_dict['led{:d}'.format(i + 1)] = pin
super().__init__(
pwm=pwm, initial_value=initial_value,
_order=pins_dict.keys(),
Expand Down Expand Up @@ -1526,8 +1526,8 @@ def __init__(self, red=None, amber=None, green=None, *,
devices['amber'] = amber
devices['green'] = green
if not all(p is not None for p in devices.values()):
raise GPIOPinMissing('%s pins must be provided' %
', '.join(devices.keys()))
raise GPIOPinMissing('{keys} pins must be provided'.format(
keys=', '.join(devices.keys())))
super().__init__(
pwm=pwm, initial_value=initial_value,
_order=devices.keys(), pin_factory=pin_factory,
Expand Down Expand Up @@ -1635,8 +1635,8 @@ def __init__(
pin_factory=None):
gpios = self.LOCATIONS.get(location, None)
if gpios is None:
raise ValueError('location must be one of: %s' %
', '.join(sorted(self.LOCATIONS.keys())))
raise ValueError('location must be one of: {locations}'.format(
locations=', '.join(sorted(self.LOCATIONS.keys()))))
super().__init__(
*gpios, pwm=pwm, initial_value=initial_value,
pin_factory=pin_factory)
Expand Down Expand Up @@ -1713,11 +1713,11 @@ def __init__(self, *labels, pwm=False, initial_value=False,
if len(labels) == 0:
labels = self.default_labels
elif len(labels) > len(pins):
raise ValueError("StatusZero doesn't support more than %d "
"labels" % len(pins))
raise ValueError("StatusZero doesn't support more than {count} "
"labels".format(count=len(pins)))
dup, count = Counter(labels).most_common(1)[0]
if count > 1:
raise ValueError("Duplicate label %s" % dup)
raise ValueError("Duplicate label {dup}".format(dup=dup))
super().__init__(
_order=labels, pin_factory=pin_factory, **{
label: LEDBoard(
Expand Down Expand Up @@ -1816,7 +1816,7 @@ def __init__(self, *labels, pwm=False, initial_value=False,
raise ValueError("StatusBoard doesn't support more than five labels")
dup, count = Counter(labels).most_common(1)[0]
if count > 1:
raise ValueError("Duplicate label %s" % dup)
raise ValueError("Duplicate label {dup}".format(dup=dup))
super().__init__(
_order=labels, pin_factory=pin_factory, **{
label: CompositeOutputDevice(
Expand Down Expand Up @@ -2591,7 +2591,9 @@ def closed(self):
def __repr__(self):
try:
self._check_open()
return "<gpiozero.Energenie object on socket %d>" % self._socket
return (
"<gpiozero.Energenie object on socket "
"{self._socket}>".format(self=self))
except DeviceClosed:
return "<gpiozero.Energenie object closed>"

Expand Down
18 changes: 9 additions & 9 deletions gpiozero/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,26 @@
# Copied from the MIT-licensed https://github.com/slezica/python-frozendict
class frozendict(Mapping):
def __init__(self, *args, **kwargs):
self.__dict = dict(*args, **kwargs)
self.__hash = None
self._dict = dict(*args, **kwargs)
self._hash = None

def __getitem__(self, key):
return self.__dict[key]
return self._dict[key]

def copy(self, **add_or_replace):
return frozendict(self, **add_or_replace)

def __iter__(self):
return iter(self.__dict)
return iter(self._dict)

def __len__(self):
return len(self.__dict)
return len(self._dict)

def __repr__(self):
return '<frozendict %s>' % repr(self.__dict)
return '<frozendict {self._dict!r}>'.format(self=self)

def __hash__(self):
if self.__hash is None:
if self._hash is None:
hashes = map(hash, self.items())
self.__hash = reduce(operator.xor, hashes, 0)
return self.__hash
self._hash = reduce(operator.xor, hashes, 0)
return self._hash
71 changes: 40 additions & 31 deletions gpiozero/devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ def __setattr__(self, name, value):
# repeating the "source" and "values" property code in myriad places
if hasattr(self, '__attrs__') and name not in self.__attrs__:
raise AttributeError(
"'%s' object has no attribute '%s'" % (
self.__class__.__name__, name))
"'{self.__class__.__name__}' object has no attribute "
"'{name}'".format(self=self, name=name))
return super().__setattr__(name, value)

def __del__(self):
Expand Down Expand Up @@ -206,7 +206,8 @@ def closed(self):
def _check_open(self):
if self.closed:
raise DeviceClosed(
'%s is closed or uninitialized' % self.__class__.__name__)
'{self.__class__.__name__} is closed or uninitialized'.format(
self=self))

def __enter__(self):
return self
Expand Down Expand Up @@ -274,7 +275,8 @@ def _default_pin_factory():
except Exception as e:
warnings.warn(
PinFactoryFallback(
'Falling back from %s: %s' % (name, str(e))))
'Falling back from {name}: {e!s}'.format(
name=name, e=e)))
raise BadPinFactory('Unable to load any default pin factory!')
elif name in default_factories:
# As above, this is a fast-path optimization to avoid loading
Expand All @@ -294,14 +296,17 @@ def _default_pin_factory():
return factory.load()()
for factory in pkg_resources.iter_entry_points(group, name.lower()):
return factory.load()()
raise BadPinFactory('Unable to find pin factory "%s"' % name)
raise BadPinFactory('Unable to find pin factory "{name}"'.format(
name=name))

def __repr__(self):
try:
self._check_open()
return "<gpiozero.%s object>" % (self.__class__.__name__)
return "<gpiozero.{self.__class__.__name__} object>".format(
self=self)
except DeviceClosed:
return "<gpiozero.%s object closed>" % (self.__class__.__name__)
return "<gpiozero.{self.__class__.__name__} object closed>".format(
self=self)

def _conflicts_with(self, other):
"""
Expand Down Expand Up @@ -397,19 +402,21 @@ def __init__(self, *args, _order=None, pin_factory=None, **kwargs):
else:
for missing_name in set(kwargs.keys()) - set(self._order):
raise CompositeDeviceBadOrder(
'%s missing from _order' % missing_name)
'{missing_name} missing from _order'.format(
missing_name=missing_name))
self._order = tuple(self._order)
for name in set(self._order) & set(dir(self)):
raise CompositeDeviceBadName(
'%s is a reserved name' % name)
'{name} is a reserved name'.format(name=name))
for dev in chain(args, kwargs.values()):
if not isinstance(dev, Device):
raise CompositeDeviceBadDevice(
"%s doesn't inherit from Device" % dev)
"{dev} doesn't inherit from Device".format(dev=dev))
self._named = frozendict(kwargs)
self._namedtuple = namedtuple(
'%sValue' % self.__class__.__name__, chain(
('device_%d' % i for i in range(len(args))), self._order))
'{self.__class__.__name__}Value'.format(self=self), chain(
('device_{i}'.format(i=i)
for i in range(len(args))), self._order))
except:
for dev in chain(args, kwargs.values()):
if isinstance(dev, Device):
Expand All @@ -425,12 +432,12 @@ def __getattr__(self, name):
try:
return self._named[name]
except KeyError:
raise AttributeError("no such attribute %s" % name)
raise AttributeError("no such attribute {name}".format(name=name))

def __setattr__(self, name, value):
# make named components read-only properties
if name in self._named:
raise AttributeError("can't set attribute %s" % name)
raise AttributeError("can't set attribute {name}".format(name=name))
return super().__setattr__(name, value)

def __repr__(self):
Expand All @@ -439,22 +446,20 @@ def __repr__(self):
named = len(self._named)
unnamed = len(self) - len(self._named)
if named > 0 and unnamed > 0:
return "<gpiozero.%s object containing %d devices: %s and %d unnamed>" % (
self.__class__.__name__,
len(self), ', '.join(self._order),
len(self) - len(self._named)
)
template = (
"<gpiozero.{self.__class__.__name__} object containing "
"{count} devices: {names} and {unnamed} unnamed>")
elif named > 0:
return "<gpiozero.%s object containing %d devices: %s>" % (
self.__class__.__name__,
len(self),
', '.join(self._order)
)
template = (
"<gpiozero.{self.__class__.__name__} object containing "
"{count} devices: {names}>")
else:
return "<gpiozero.%s object containing %d unnamed devices>" % (
self.__class__.__name__,
len(self)
)
template = (
"<gpiozero.{self.__class__.__name__} object containing "
"{count} unnamed devices>")
return template.format(
self=self, count=len(self), names=', '.join(self._order),
unnamed=len(self) - len(self._named))
except DeviceClosed:
return super().__repr__()

Expand Down Expand Up @@ -587,10 +592,14 @@ def value(self):

def __repr__(self):
try:
return "<gpiozero.%s object on pin %r, is_active=%s>" % (
self.__class__.__name__, self.pin, self.is_active)
return (
"<gpiozero.{self.__class__.__name__} object on pin "
"{self.pin!r}, is_active={self.is_active}>".format(
self=self))
except DeviceClosed:
return "<gpiozero.%s object closed>" % self.__class__.__name__
return (
"<gpiozero.{self.__class__.__name__} object closed>".format(
self=self))


def _devices_shutdown():
Expand Down
24 changes: 14 additions & 10 deletions gpiozero/input_devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,14 @@ def __init__(self, pin=None, *, pull_up=False, active_state=None,
if pull_up is None:
if active_state is None:
raise PinInvalidState(
'Pin %d is defined as floating, but "active_state" is not '
'defined' % self.pin.number)
'Pin {self.pin.number} is defined as floating, but '
'"active_state" is not defined'.format(self=self))
self._active_state = bool(active_state)
else:
if active_state is not None:
raise PinInvalidState(
'Pin %d is not floating, but "active_state" is not None' %
self.pin.number)
'Pin {self.pin.number} is not floating, but '
'"active_state" is not None'.format(self=self))
self._active_state = False if pull_up else True
self._inactive_state = not self._active_state

Expand All @@ -108,8 +108,10 @@ def pull_up(self):

def __repr__(self):
try:
return "<gpiozero.%s object on pin %r, pull_up=%s, is_active=%s>" % (
self.__class__.__name__, self.pin, self.pull_up, self.is_active)
return (
"<gpiozero.{self.__class__.__name__} object on pin "
"{self.pin!r}, pull_up={self.pull_up}, "
"is_active={self.is_active}>".format(self=self))
except:
return super().__repr__()

Expand Down Expand Up @@ -280,8 +282,9 @@ def __repr__(self):
if self.partial or self._queue.full.is_set():
return super().__repr__()
else:
return "<gpiozero.%s object on pin %r, pull_up=%s>" % (
self.__class__.__name__, self.pin, self.pull_up)
return (
"<gpiozero.{self.__class__.__name__} object on pin "
"{self.pin!r}, pull_up={self.pull_up}>".format(self=self))

@property
def queue_len(self):
Expand Down Expand Up @@ -1150,8 +1153,9 @@ def __init__(self, a, b, *, bounce_time=None, max_steps=16,
def __repr__(self):
try:
self._check_open()
return "<gpiozero.%s object on pins %r and %r>" % (
self.__class__.__name__, self.a.pin, self.b.pin)
return (
"<gpiozero.{self.__class__.__name__} object on pins "
"{self.a.pin!r} and {self.b.pin!r}>".format(self=self))
except DeviceClosed:
return super().__repr__()

Expand Down

0 comments on commit 5ea3c6a

Please sign in to comment.