Python
Style Guide

Why?

  • Improve readability/understanding
  • Ensure (cross-)functionality

Important

Naming

  • Stick to PEP 8 when you
  • lowercase package & module names
  • CamelCase classes
  • lower_case methods and attributes
  • UPPER_CASE constants
  • Use underscore prefix for _internal_attributes
  • Use underscore suffix to resolve naming conflicts:
    class_ > cls
  • Indent with 4 spaces, not tabs!

New-Style Classes and super

Don't

						class A:
						    def __init__(self):
						        pass

						class B(A):
						    def __init__(self):
						        A.__init__()
						        pass
					
Do

						class A(object):
						    def __init__(self):
						        pass

						class B(A):
						    def __init__(self):
						        super(B, self).__init__()
						        pass
					

Initialize Class attributes

Don't

						class C(B):
						    def __init__(self):
						        super(C, self).__init__()
						    def compute_result(self):
						        self.result = 1
					
Do

						class C(B):
						    def __init__(self):
						        super(C, self).__init__()
						        self.result = None
						    def compute_result(self):
						        self.result = 1
					

Other

Nice to Have

  • Keep namespaces clean, don't from X import *
  • Use descriptive names (more writing = less confusion)
  • Use __init__.py to improve your package's structure
    • __all__ = [...] specifies what from module import * imports
    • Don't force users to from dlmodule.models.UNet import UNet, instead put from UNet import UNet in the __init__.py for models

Resources