Skip to content

Instantly share code, notes, and snippets.

View DavidAntliff's full-sized avatar

David Antliff DavidAntliff

View GitHub Profile
@DavidAntliff
DavidAntliff / coerce_iterable.py
Created March 15, 2017 01:38
Coerce a scalar or sequence into an iterable
def coerce_iterable(scalar_or_sequence):
"""If scalar_or_sequence is not iterable, wrap it so that the return value is."""
try:
_ = tuple(x for x in scalar_or_sequence)
result = scalar_or_sequence
except TypeError:
# The user has probably specified a single entity and forgotten to
# define it as a proper tuple, so be friendly and handle as a scalar instance:
result = (scalar_or_sequence,)
return result
@DavidAntliff
DavidAntliff / partition_by_set.py
Last active March 15, 2017 01:37
Python: partition a string with a set of delimiters
import re
def partition(string, delimiters):
"""Split a string into a (head, sep, tail) tuple based on the
first occurrence of a delimiter in the string.
This is similar to str.partition() except it accepts a set of delimiters.
The set can be a list/tuple of characters, or a string."""
seps = "".join(delimiters)
return re.match(r"([^{seps}]*)([{seps}]?)(.*)".format(seps=seps), string).groups()
@DavidAntliff
DavidAntliff / multi_option.py
Created November 30, 2016 00:33
Python: accept multiple instances of a command line argument
"""
Copyright 2016 David Antliff; this file is licensed under the terms of the Apache license version 2.0. For a full copy of the license, see https://www.apache.org/licenses/LICENSE-2.0
Accept two styles of repeated options on the command line.
Style 1 - each instance repeats the option itself. E.g.
$ python prog --option A --option B
Style 2 - each instance occurs after a single instance of the option. E.g.