Skip to content

Instantly share code, notes, and snippets.

@jlnwlf
Last active April 21, 2020 03:26
Show Gist options
  • Save jlnwlf/8332392 to your computer and use it in GitHub Desktop.
Save jlnwlf/8332392 to your computer and use it in GitHub Desktop.
Useful Python snippets

General tips and guidelines for Python development

Code management

  • Always prefer huge modules (i.e. few big source files) instead of Java's "one class, one file" policy. Or you can use Python packages instead (directory with __init__.py file) to organize multiple files.
  • This tutorial about directory structure for Python projects.
  • When creating "abstract" classes with some default methods, raise NotImplementedError in the base class. You can do so also with data attributes with @property in the base class like this.

Coding standards from Python PEP 8 Coding standards

General coding tips

  • Do not use (object) attributes if the attribute is not used at least 2 times in the object, otherwise use a local method argument.

Tools

# defaultdict (http://docs.python.org/2/library/collections.html#collections.defaultdict)
# lets create default keys as we access them.
import collections
# It uses the default factory str to build empty elements automatically from this class.
# (Any class with 0 argument works here)
l = collections.defaultdict(str)
l[123] # It will create an empty str object at non-existent key 123
print dict(l)
# Unlimited "clean" defaultdict implementation for tree-like structure (Source: http://ohuiginn.net/mt/2010/07/nested_dictionaries_in_python.html)
class NestedDict(dict):
def __getitem__(self, key):
if key in self: return self.get(key)
return self.setdefault(key, NestedDict())
# More optimized version
class _NestedDict(dict):
__slots__ = ()
def __missing__(self, key):
self[key] = value = _NestedDict()
return value
# Correct way to use path concatenation for cross-platform use
os.listdir(os.path.join('mydir', 'subdir'))
# split seq in length size chunks list (works even if len(seq) is not a multiple of length)
[seq[i:i + length] for i in range(0, len(seq), length)]
# "2-level" nested list comprehension
test = {
"foo": (
u"Some",
u"Text",
),
"bar": (
u"I want in a PLAIN list",
)
}
plain_list = [x for y in test.values() for x in y] # [u'Some', u'Text', u'I want in a PLAIN list']
# Split to two different variables at ' '
(foo, bar) = baz.split(' ', 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment