Skip to content

Instantly share code, notes, and snippets.

@domibarton
Last active March 4, 2017 09:42
Show Gist options
  • Save domibarton/1a69f721b7a72916c2d3ace3ea740ecf to your computer and use it in GitHub Desktop.
Save domibarton/1a69f721b7a72916c2d3ace3ea740ecf to your computer and use it in GitHub Desktop.
class KeyValue(unicode):
'''
This class can be used to represent newline-separated colon-based and
key-value strings. This sounds a bit complicated, but in fact it's really
simple and straight forward. It's basically an unicode class on steroids.
Just create a new instance and define colon-based key-value strings in the
constructor. Each line should contain one key-value pair, for example:
```
spam: eggs
foo: bar
hello: world
```
Printing a KeyValue object will lead to the same result as printing the
unicode itself, it will simply return the unformated key-value string. However,
the class also implements an iterator which means you can properly iterate
over all key-value pairs.
Here's an example:
```
>>> obj = KeyValue('foo:bar\nspam:eggs')
>>> print(obj)
foo:bar
spam:eggs
>>> print(obj.__iter__())
<generator object __iter__ at 0x101d4f230>
>>> for key, value in obj:
>>> print('{} = {}'.format(key, value))
foo = bar
spam = eggs
```
Please note the iterator is implemented as a a generator!
'''
def __iter__(self):
lines = self.strip().split('\n')
for line in lines:
pair = line.split(':')
if len(pair) >= 2:
key = pair.pop(0).strip()
value = ' '.join(pair).strip()
yield (key, value)
raise StopIteration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment