Skip to content

Instantly share code, notes, and snippets.

@vitiral
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitiral/de9b54d30547ddd28ec4 to your computer and use it in GitHub Desktop.
Save vitiral/de9b54d30547ddd28ec4 to your computer and use it in GitHub Desktop.
Functions that should be in the python builtins module
from enum import Enum
def enum(name, attrs=None):
'''enum generator function
Creates an Enum type. attrs can be: set, list, tuples or a dictionary.
The behavior is as follows:
- dictionaries and lists/tuples of the form [(name, key), (name2, key2), ...] will behave
as expected. (dictionaries will have their items() method called
- sets will be converted to zip(sorted(attrs), range(len(attrs)))
- lists/tuples without embeded tuples will do the same without sorting
Can be called in two forms:
enum(name, attrs)
OR
enum(attrs) # name will == 'enum'
'''
if attrs is None:
# use default name, attrs becomes first argument
name, attrs = 'enum', name
if isinstance(attrs, dict):
attrs = attrs.items()
elif isinstance(attrs, set):
attrs = zip(sorted(attrs), range(len(attrs)))
elif not isinstance(attrs[0], (tuple, list)):
attrs = zip(attrs, range(len(attrs)))
return Enum(name, attrs)
def isiter(obj, exclude=(str, bytes, bytearray)):
'''Returns True if object is an iterator.
Returns False for str, bytes and bytearray objects
by default'''
return (False if isinstance(obj, exclude)
else True if hasattr(obj, '__iter__')
else False)
# python3
def encode(data, encoding="utf-8", errors="strict"):
'''Always outputs bytes if possible'''
if isinstance(data, (bytes, bytearray)):
return bytes(data)
elif hasattr(data, 'encode'):
return data.encode(encoding, errors)
elif hasattr(data, 'decode'):
return(decode(encode(data, encoding, errors), encoding, errors))
else:
raise TypeError("Cannot encode data: {}".format(data))
def decode(data, encoding="utf-8", errors="strict"):
'''Always outputs str if possible'''
if isinstance(data, str):
return data
elif hasattr(data, 'decode'):
return data.decode(encoding, errors)
elif hasattr(data, 'encode'):
return(encode(decode(data, encoding, errors), encoding, errors))
else:
raise TypeError("Cannot decode data: {}".format(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment