studioimaginaire / phue

A Python library for the Philips Hue system
Other
1.54k stars 266 forks source link

Add better __repr__ and __str__ methods to classes #202

Open sicada opened 1 year ago

sicada commented 1 year ago

The current Bridge, Light, Sensor, Group, and Scene classes have incorrect, inconsistent, or missing methods for their __repr__ and __str__ attributes. This PR adds consistency to those classes by defining a python-parseable __repr__ value **, and a human-readable __str__ value.

** NOTE: The __repr__ method is meant to return a string that represents that object in a serialized format. If done correctly, that string should be able to be fed back into python (e.g. via eval()) to recreate the original object instance with some level of usefulness. I didn't fully serialize the phue classes, but captured the most important values needed to recreate similar class instances from the __repr__ output.

Example output with the new methods in place:

>>> repr(b)
'phue.Bridge(ip=192.168.1.5, username=IG4iYhueTest, config_file_path=/home/user/.python_hue)'
>>> str(b)
'My Test Hue (ip=192.168.1.5)'

>>> l = b.lights[0]
>>> repr(l)
'phue.Light(bridge=192.168.1.5, light_id=1)'
>>> str(l)
'Vanity Color Left (id=1)'

>>> g = b.groups[0]
>>> repr(g)
'phue.Group(bridge=192.168.1.5, group_id=1)'
>>> str(g)
'Downstairs Bathroom (id=1)'

>>> s = list(b.sensors)[0]
>>> repr(s)
'phue.Sensor(bridge=192.168.7.5, sensor_id=1)'
>>> str(s)
'Daylight (id=1)'

>>> sc = b.scenes[0]
>>> repr(sc)
'phue.Scene(sid=pNvQwaPktyOf56O, name=Nightlight, lights=[1, 2, 3, 15])'
>>> str(sc)
'Nightlight (id=pNvQwaPktyOf56O)'