Skip to content

Commit 0825a60

Browse files
Add black code formatter (theolind#235)
* Add config and tools for black * Run black
1 parent c45c596 commit 0825a60

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+2020
-1607
lines changed

.pre-commit-config.yaml

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# See https://pre-commit.com/
2+
# See https://github.com/psf/black#version-control-integration
3+
repos:
4+
- repo: https://github.com/psf/black
5+
rev: stable
6+
hooks:
7+
- id: black
8+
language_version: python3.6

Makefile

+9-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
.PHONY: help build clean clean-build clean-pyc coverage lint release test-release test test-all
1+
.PHONY: help black black-format build clean clean-build clean-pyc coverage lint release test-release test test-all
22

33
help:
4+
@echo "black - run black code formatter check"
5+
@echo "black-format - run black code formatter format"
46
@echo "build - build a distribution"
57
@echo "clean - run all clean operations"
68
@echo "clean-build - remove build artifacts"
@@ -12,6 +14,12 @@ help:
1214
@echo "test - run tests quickly with the default Python"
1315
@echo "test-all - run tests on every Python version with tox"
1416

17+
black:
18+
black --check ./
19+
20+
black-format:
21+
black ./
22+
1523
build:
1624
python setup.py sdist bdist_wheel
1725

README.md

+9
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,15 @@ Use the Makefile to run common development tasks.
228228
make
229229
```
230230

231+
### Code formatting
232+
233+
We use black code formatter to automatically format the code.
234+
This requires Python 3.6 for development.
235+
236+
```sh
237+
black ./
238+
```
239+
231240
### Release
232241

233242
See the [release instructions](RELEASE.md).

async_main.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
def event(message):
1212
"""Handle mysensors updates."""
13-
print('sensor_update ' + str(message.node_id))
13+
print("sensor_update " + str(message.node_id))
1414

1515

1616
LOOP = asyncio.get_event_loop()
@@ -19,8 +19,8 @@ def event(message):
1919
try:
2020
# To create a serial gateway.
2121
GATEWAY = mysensors.AsyncSerialGateway(
22-
'/dev/ttyACM0', loop=LOOP, event_callback=event,
23-
protocol_version='2.1')
22+
"/dev/ttyACM0", loop=LOOP, event_callback=event, protocol_version="2.1"
23+
)
2424
LOOP.run_until_complete(GATEWAY.start())
2525
LOOP.run_forever()
2626
except KeyboardInterrupt:

main.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ def event(message):
1313

1414
# To create a serial gateway.
1515
GATEWAY = mysensors.SerialGateway(
16-
'/dev/ttyACM0', event_callback=event, protocol_version='2.0')
16+
"/dev/ttyACM0", event_callback=event, protocol_version="2.0"
17+
)
1718

1819
# To create a TCP gateway.
1920
# GATEWAY = mysensors.TCPGateway('127.0.0.1', event_callback=event)

mqtt.py

+13-8
Original file line numberDiff line numberDiff line change
@@ -26,35 +26,40 @@ def subscribe(self, topic, callback, qos):
2626

2727
def _message_callback(mqttc, userdata, msg):
2828
"""Callback added to callback list for received message."""
29-
callback(msg.topic, msg.payload.decode('utf-8'), msg.qos)
29+
callback(msg.topic, msg.payload.decode("utf-8"), msg.qos)
3030

3131
self._mqttc.subscribe(topic, qos)
3232
self._mqttc.message_callback_add(topic, _message_callback)
3333
self.topics[topic] = callback
3434

3535
def start(self):
3636
"""Run the MQTT client."""
37-
print('Start MQTT client')
37+
print("Start MQTT client")
3838
self._mqttc.loop_start()
3939

4040
def stop(self):
4141
"""Stop the MQTT client."""
42-
print('Stop MQTT client')
42+
print("Stop MQTT client")
4343
self._mqttc.disconnect()
4444
self._mqttc.loop_stop()
4545

4646

4747
def event(message):
4848
"""Callback for mysensors updates."""
49-
print('sensor_update ' + str(message.node_id))
49+
print("sensor_update " + str(message.node_id))
5050

5151

52-
MQTTC = MQTT('localhost', 1883, 60)
52+
MQTTC = MQTT("localhost", 1883, 60)
5353
MQTTC.start()
5454

5555
GATEWAY = mysensors.MQTTGateway(
56-
MQTTC.publish, MQTTC.subscribe, in_prefix='mygateway1-out',
57-
out_prefix='mygateway1-in', retain=True, event_callback=event,
58-
protocol_version='2.0')
56+
MQTTC.publish,
57+
MQTTC.subscribe,
58+
in_prefix="mygateway1-out",
59+
out_prefix="mygateway1-in",
60+
retain=True,
61+
event_callback=event,
62+
protocol_version="2.0",
63+
)
5964

6065
GATEWAY.start()

mysensors/__init__.py

+57-31
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ class Gateway:
2424

2525
# pylint: disable=too-many-instance-attributes
2626

27-
def __init__(self, event_callback=None, protocol_version='1.4'):
27+
def __init__(self, event_callback=None, protocol_version="1.4"):
2828
"""Set up Gateway."""
2929
protocol_version = safe_is_version(protocol_version)
3030
self.const = get_const(protocol_version)
@@ -42,7 +42,7 @@ def __init__(self, event_callback=None, protocol_version='1.4'):
4242

4343
def __repr__(self):
4444
"""Return the representation."""
45-
return '<{}>'.format(self.__class__.__name__)
45+
return "<{}>".format(self.__class__.__name__)
4646

4747
def logic(self, data):
4848
"""Parse the data and respond to it appropriately.
@@ -53,13 +53,12 @@ def logic(self, data):
5353
try:
5454
msg = Message(data)
5555
except ValueError as exc:
56-
_LOGGER.warning('Not a valid message: %s', exc)
56+
_LOGGER.warning("Not a valid message: %s", exc)
5757
return None
5858
try:
5959
msg.validate(self.protocol_version)
6060
except vol.Invalid as exc:
61-
_LOGGER.warning(
62-
'Invalid %s: %s', msg, humanize_error(msg.__dict__, exc))
61+
_LOGGER.warning("Invalid %s: %s", msg, humanize_error(msg.__dict__, exc))
6362
return None
6463

6564
msg.gateway = self
@@ -102,35 +101,39 @@ def is_sensor(self, sensorid, child_id=None):
102101
"""Return True if a sensor and its child exist."""
103102
ret = sensorid in self.sensors
104103
if not ret:
105-
_LOGGER.warning('Node %s is unknown', sensorid)
104+
_LOGGER.warning("Node %s is unknown", sensorid)
106105
if ret and child_id is not None:
107106
ret = child_id in self.sensors[sensorid].children
108107
if not ret:
109-
_LOGGER.warning('Child %s is unknown', child_id)
110-
if not ret and parse_ver(self.protocol_version) >= parse_ver('2.0'):
111-
_LOGGER.info('Requesting new presentation for node %s',
112-
sensorid)
108+
_LOGGER.warning("Child %s is unknown", child_id)
109+
if not ret and parse_ver(self.protocol_version) >= parse_ver("2.0"):
110+
_LOGGER.info("Requesting new presentation for node %s", sensorid)
113111
msg = Message(gateway=self).modify(
114-
node_id=sensorid, child_id=SYSTEM_CHILD_ID,
112+
node_id=sensorid,
113+
child_id=SYSTEM_CHILD_ID,
115114
type=self.const.MessageType.internal,
116-
sub_type=self.const.Internal.I_PRESENTATION)
115+
sub_type=self.const.Internal.I_PRESENTATION,
116+
)
117117
if self._route_message(msg):
118118
self.tasks.add_job(msg.encode)
119119
return ret
120120

121121
def _route_message(self, msg):
122-
if not isinstance(msg, Message) or \
123-
msg.type == self.const.MessageType.presentation:
122+
if (
123+
not isinstance(msg, Message)
124+
or msg.type == self.const.MessageType.presentation
125+
):
124126
return None
125-
if (msg.node_id not in self.sensors
126-
or msg.type == self.const.MessageType.stream
127-
or not self.sensors[msg.node_id].new_state):
127+
if (
128+
msg.node_id not in self.sensors
129+
or msg.type == self.const.MessageType.stream
130+
or not self.sensors[msg.node_id].new_state
131+
):
128132
return msg
129133
self.sensors[msg.node_id].queue.append(msg.encode())
130134
return None
131135

132-
def set_child_value(
133-
self, sensor_id, child_id, value_type, value, **kwargs):
136+
def set_child_value(self, sensor_id, child_id, value_type, value, **kwargs):
134137
"""Add a command to set a sensor value, to the queue.
135138
136139
A queued command will be sent to the sensor when the gateway
@@ -145,12 +148,18 @@ def set_child_value(
145148
return
146149
if self.sensors[sensor_id].new_state:
147150
self.sensors[sensor_id].set_child_value(
148-
child_id, value_type, value,
149-
children=self.sensors[sensor_id].new_state)
151+
child_id, value_type, value, children=self.sensors[sensor_id].new_state
152+
)
150153
else:
151-
self.tasks.add_job(partial(
152-
self.sensors[sensor_id].set_child_value, child_id, value_type,
153-
value, **kwargs))
154+
self.tasks.add_job(
155+
partial(
156+
self.sensors[sensor_id].set_child_value,
157+
child_id,
158+
value_type,
159+
value,
160+
**kwargs
161+
)
162+
)
154163

155164
def send(self, message):
156165
"""Write a message to the arduino gateway."""
@@ -177,25 +186,42 @@ class BaseSyncGateway(Gateway):
177186
"""MySensors base sync gateway."""
178187

179188
def __init__(
180-
self, transport, *args, persistence=False,
181-
persistence_file='mysensors.pickle', **kwargs):
189+
self,
190+
transport,
191+
*args,
192+
persistence=False,
193+
persistence_file="mysensors.pickle",
194+
**kwargs
195+
):
182196
"""Set up gateway."""
183197
super().__init__(*args, **kwargs)
184198
self.tasks = SyncTasks(
185-
self.const, persistence, persistence_file, self.sensors, transport)
199+
self.const, persistence, persistence_file, self.sensors, transport
200+
)
186201

187202

188203
class BaseAsyncGateway(Gateway):
189204
"""MySensors base async gateway."""
190205

191206
def __init__(
192-
self, transport, *args, loop=None, persistence=False,
193-
persistence_file='mysensors.pickle', **kwargs):
207+
self,
208+
transport,
209+
*args,
210+
loop=None,
211+
persistence=False,
212+
persistence_file="mysensors.pickle",
213+
**kwargs
214+
):
194215
"""Set up gateway."""
195216
super().__init__(*args, **kwargs)
196217
self.tasks = AsyncTasks(
197-
self.const, persistence, persistence_file, self.sensors,
198-
transport, loop=loop)
218+
self.const,
219+
persistence,
220+
persistence_file,
221+
self.sensors,
222+
transport,
223+
loop=loop,
224+
)
199225

200226
async def start(self):
201227
"""Start the gateway and task allow tasks to be scheduled."""

mysensors/cli/__init__.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@
88
from mysensors.cli.gateway_serial import async_serial_gateway, serial_gateway
99
from mysensors.cli.gateway_tcp import async_tcp_gateway, tcp_gateway
1010

11-
SETTINGS = dict(help_option_names=['-h', '--help'])
11+
SETTINGS = dict(help_option_names=["-h", "--help"])
1212

1313

1414
@click.group(
15-
options_metavar='', subcommand_metavar='<command>',
16-
context_settings=SETTINGS)
17-
@click.option('--debug', is_flag=True, help='Start pymysensors in debug mode.')
15+
options_metavar="", subcommand_metavar="<command>", context_settings=SETTINGS
16+
)
17+
@click.option("--debug", is_flag=True, help="Start pymysensors in debug mode.")
1818
@click.version_option(__version__)
1919
def cli(debug):
2020
"""Run pymysensors as an app for testing purposes."""

0 commit comments

Comments
 (0)