Python Design

From Smithnet Wiki
Jump to navigation Jump to search

Functions

  • Do one thing and do it well
    • Should be at the same level of abstraction
  • Command-query separation: should either make some change or return data
  • Only request information it needs
  • Keep the number of paramters minimal
    • An indication of how focused the function is
  • Don't create an use an object in the same place
    • Use dependency injection
  • Don't use flag arguments
    • can mean the funcrion should be two distinct functions to handle each case
  • Functions are objects, so can be passed around

Classes

  • Keep classes small
    • Typically either data focused (structure) or behaviour focussed (methods)
  • Make classes east to use as possible
    • eg properties instead of methods
    • use @property, @cached_property or @lru_cache
    • __repr__ for developers, __str__ for users
  • Use Dependency Injection
    • Don't create objects in the class, pass as arguments
  • Make sure a class is really needed
    • Classes are useful for multiple instances. If only one is needed, could be just a module function.

Protocols

  • Classes derived from Protcol define an interface with their attributes
  • Duck typing means another type of object that has at least the same attributes as the interface can be passed to it
  • Alternative to subclassing