A collection of design patterns/idioms in Python

Overview

python-patterns

A collection of design patterns and idioms in Python.

Current Patterns

Creational Patterns:

Pattern Description
abstract_factory use a generic function with specific factories
borg a singleton with shared-state among instances
builder instead of using multiple constructors, builder object receives parameters and returns constructed objects
factory delegate a specialized function/method to create instances
lazy_evaluation lazily-evaluated property pattern in Python
pool preinstantiate and maintain a group of instances of the same type
prototype use a factory and clones of a prototype for new instances (if instantiation is expensive)

Structural Patterns:

Pattern Description
3-tier data<->business logic<->presentation separation (strict relationships)
adapter adapt one interface to another using a white-list
bridge a client-provider middleman to soften interface changes
composite lets clients treat individual objects and compositions uniformly
decorator wrap functionality with other functionality in order to affect outputs
facade use one class as an API to a number of others
flyweight transparently reuse existing instances of objects with similar/identical state
front_controller single handler requests coming to the application
mvc model<->view<->controller (non-strict relationships)
proxy an object funnels operations to something else

Behavioral Patterns:

Pattern Description
chain_of_responsibility apply a chain of successive handlers to try and process the data
catalog general methods will call different specialized methods based on construction parameter
chaining_method continue callback next object method
command bundle a command and arguments to call later
iterator traverse a container and access the container's elements
iterator (alt. impl.) traverse a container and access the container's elements
mediator an object that knows how to connect other objects and act as a proxy
memento generate an opaque token that can be used to go back to a previous state
observer provide a callback for notification of events/changes to data
publish_subscribe a source syndicates events/data to 0+ registered listeners
registry keep track of all subclasses of a given class
specification business rules can be recombined by chaining the business rules together using boolean logic
state logic is organized into a discrete number of potential states and the next state that can be transitioned to
strategy selectable operations over the same data
template an object imposes a structure but takes pluggable components
visitor invoke a callback for all items of a collection

Design for Testability Patterns:

Pattern Description
dependency_injection 3 variants of dependency injection

Fundamental Patterns:

Pattern Description
delegation_pattern an object handles a request by delegating to a second object (the delegate)

Others:

Pattern Description
blackboard architectural model, assemble different sub-system knowledge to build a solution, AI approach - non gang of four pattern
graph_search graphing algorithms - non gang of four pattern
hsm hierarchical state machine - non gang of four pattern

Videos

Design Patterns in Python by Peter Ullrich

Sebastian Buczyński - Why you don't need design patterns in Python?

You Don't Need That!

Pluggable Libs Through Design Patterns

Contributing

When an implementation is added or modified, please review the following guidelines:

Output

All files with example patterns have ### OUTPUT ### section at the bottom (migration to OUTPUT = """...""" is in progress).

Run append_output.sh (e.g. ./append_output.sh borg.py) to generate/update it.

Docstrings

Add module level description in form of a docstring with links to corresponding references or other useful information.

Add "Examples in Python ecosystem" section if you know some. It shows how patterns could be applied to real-world problems.

facade.py has a good example of detailed description, but sometimes the shorter one as in template.py would suffice.

In some cases class-level docstring with doctest would also help (see adapter.py) but readable OUTPUT section is much better.

Python 2 compatibility

To see Python 2 compatible versions of some patterns please check-out the legacy tag.

Update README

When everything else is done - update corresponding part of README.

Travis CI

Please run tox or tox -e ci37 before submitting a patch to be sure your changes will pass CI.

You can also run flake8 or pytest commands manually. Examples can be found in tox.ini.

Contributing via issue triage Open Source Helpers

You can triage issues and pull requests which may include reproducing bug reports or asking for vital information, such as version numbers or reproduction instructions. If you would like to start triaging issues, one easy way to get started is to subscribe to python-patterns on CodeTriage.

Comments
  • Updating the source to Python 3?

    Updating the source to Python 3?

    Just a quick comment--looking over the source, do you think it'd be a good idea to update to Python 3, e.g. using type annotations and Python 3 syntax?

    enhancement 
    opened by bjd2385 16
  • ENH+BF: fix up of some tests/docs to pass with python2.7, testing on travis, consistent shebanging,

    ENH+BF: fix up of some tests/docs to pass with python2.7, testing on travis, consistent shebanging,

    I really loved the idea and the collection so decided to contribute a bit ;)

    https://travis-ci.org/yarikoptic/python-patterns/builds/130877280 should eventually reflect current state of things -- either tests pass as is or more things to be done

    Please enable travis for your project @faif -- it is easy, just go to http://travis-ci.org, authenticate through github, click toggle for this repository

    I have already complained in #143 about necessity to have clear copyright/license statement(s) so this code could e.g. be actually used/redistributed etc. Ideally the most permissive license (BSD-2 or -3 or MIT) would be the best fit.

    Also would be nice to make all code PEP8 compliant. I have added call to flake8 in travis.yml but ignoring its failure atm. Didn't want to introduce big "stylistic" changes without "go ahead"

    opened by yarikoptic 13
  • [Infrastructure] Testing outputs

    [Infrastructure] Testing outputs

    update on idea of testing outputs as docstrings (e.g. with python -m doctest): I couldn't find easy way to generate docstrings for def main()

    By "testing outputs" I mean to compare script output with ### OUTPUT ### section at the bottom of the file. Structuring scripts like that:

    def main():
        ...
    
    if __name__ == "__main__":
       main()
    

    allows imports of main in tests to evaluate and compare outputs.

    It would also be more convenient to have ### OUTPUT ### section as variable or docstring, so we do not need to parse file for such comparisons

    enhancement 
    opened by gyermolenko 11
  • When flyweight.py is run as skript it raises an error

    When flyweight.py is run as skript it raises an error

    When flyweight.py is run as skript the following output is generated:

    <Card: 9h> <Card: 9h>
    True True
    50022776 50022776
    True
    False
    Traceback (most recent call last):
      File "D:\Users\Florian\Documents\GitHub\python-patterns\flyweight.py", line 92, in <module>
        instances_pool = getattr(Card2, 'pool')
    AttributeError: type object 'Card2' has no attribute 'pool'
    
    opened by fkromer 11
  • Your code is too weak for PEP8. You lack DISCIPLINE

    Your code is too weak for PEP8. You lack DISCIPLINE

    Good morning how are you? This is Arnold! Nice to meet you. I like your project, but your code looks gurly and lacks discipline! Here is a pull request to pump it up. You must apply it, do it now!

    opened by pyarnold 11
  • Made builder pattern much simpler by removing unnecessary class.

    Made builder pattern much simpler by removing unnecessary class.

    This follows the motto "a class with only one method that actually does anything should be a function", with the result that using the director function requires one line of code instead of 5.

    opened by spookylukey 9
  • Python Patterns Organization

    Python Patterns Organization

    Hi @faif, what do you think about to creating a GitHub organization for a central place of python pattern related stuff? I have a lot of python pattern example references to books here (paste "python" in the search field) which make more sense in a more "python oriented" context. But I think these book references would "waste" your repository. But they would be quite suitable in an organization beside your repository...

    enhancement 
    opened by fkromer 7
  • Is Borg really implemented right ?

    Is Borg really implemented right ?

    I thought that the point of Borg was to allow subclassing. However, the implementation doesn't match expectations in this case:

    class Borg:
        __shared_state = {}
    
        def __init__(self):
            self.__dict__ = self.__shared_state
            self.state = 'Running'
    
        def __str__(self):
            return self.state
    
    instance0 = Borg()
    instance1 = Borg()
    
    instance0.state = 'Idle'
    
    print instance1  # prints 'Idle', instead of 'Running', as expected
    
    borg = Borg()
    borg.state = 'Idle'
    
    
    class YourBorg(Borg):
        pass
    
    borg = YourBorg()
    print borg  # prints 'Running' instead of 'Idle', **not** as expected
    

    Are you sure that Borg supports setting attributes in the constructor ?

    It looks like it defeats the purpose of Borg...

    enhancement 
    opened by jpic 7
  • Short descriptions

    Short descriptions

    It would be useful to have some more detailed descriptions for each pattern. I would put them in the comments above the code. The main questions would be:

    • What the pattern is?
    • What the current example does?
    • Where can the pattern be used practically (or is used in known open-source projects)?

    Some of the patterns have comments or are obvious, but not all of them. Also, I think, that people with different computer science knowledge will check them, so it would be valuable to describe the patterns to them.

    enhancement 
    opened by archatas 6
  • repository structure

    repository structure

    Hello, I found this repository very useful. For improve readability it would be nice to structure this repository in modules/ folder (creational, structural).

    What do you think about it?

    enhancement 
    opened by bonesmccoy 5
  • Enhance documentation with brief, high-level descriptions/usage of patterns

    Enhance documentation with brief, high-level descriptions/usage of patterns

    I'd hate to think that I'm the only one of the thousands of people who have starred this project, but I would greatly benefit from a list of the purposes of each pattern in the README document. It would keep me/us/others from having to peruse each individual module to determine their use when there are so many other interesting things that that equally demand attention.

    Thoughts?

    opened by dsoprea 5
  • Support for type hints

    Support for type hints

    Some files have type hints and others do not. I think writing type hints make it easier to understand the patterns. I suggest to write type hints and if its okay, I will work some.

    And there are two typing style now in python, so I would ask which is good, >=3.9 style or <3.9 style. (mypy started to support for >=3.9 style just two days ago. https://mypy-lang.blogspot.com/2021/01/mypy-0800-released.html)

    enhancement 
    opened by yhay81 1
  • [Suggestion] Notebook version of the repo

    [Suggestion] Notebook version of the repo

    The way this repo is structured can be hard to read at times. Have you considered creating a jupyter notebook version of this repo?

    Pros

    • Better formatting of texts
    • Code output can be easily shown
    • The illustration images can be added on the same notebook

    Overall it would be a nicer learning experience. I have created one example here.

    enhancement 
    opened by modasserbillah 4
  • [suggestion] Listing anti-patterns in README

    [suggestion] Listing anti-patterns in README

    I think listing anti-patterns with some basic reasoning about "why not" is a good idea.

    Example - singleton. Although #256 has "won't fix" label

    • it is in PRs section, and people (if searching history at all) are searching issues first.
    • it was misspelled, Singelton instead of Singleton, therefore impossible to find

    Listing most popular anti-patterns (without actual implementation) should allow people to find the name from readme

    • immediately assume it was'n just missed by mistake
    • see why it is not welcome for python projects
    enhancement 
    opened by gyermolenko 1
  • [Infrastructure] Code coverage

    [Infrastructure] Code coverage

    As far as I know almost always coverage is used to see "test coverage". For unused branches/variables etc there are linters, dead-code finders (such as vulture or dead).

    So I don't think code coverage is important to extent of running run_all.sh script.

    I would like to

    • remove run_all.sh
    • collect coverage
      • only for tests
      • only for one python branch (e.g. 3.7) (although it is possible to do coverage run -p and then coverage combine)
    enhancement 
    opened by gyermolenko 4
  • [Question] Functional Programming Patterns

    [Question] Functional Programming Patterns

    Would you accept PRs about functional programming patterns @faif ? Would probably imply some project restructuring (e.g. putting dirs "behavioral" and "structural" into "oop").

    question 
    opened by fkromer 7
Owner
Sakis Kasampalis
I like Programming and I enjoy writing code in pragmatic languages, without being dogmatic about them. My principle is to use the right tool for the job
Sakis Kasampalis
Leveraging Unique CPS Properties to Design Better Privacy-Enhancing Algorithms

Differential_Privacy_CPS Python implementation of the research paper Leveraging Unique CPS Properties to Design Better Privacy-Enhancing Algorithms Re

Shubhesh Anand 2 Dec 14, 2022
Algorithms-in-Python - Programs related to DSA in Python for placement practice

Algorithms-in-Python Programs related to DSA in Python for placement practice CO

MAINAK CHAUDHURI 2 Feb 2, 2022
Minimal examples of data structures and algorithms in Python

Pythonic Data Structures and Algorithms Minimal and clean example implementations of data structures and algorithms in Python 3. Contributing Thanks f

Keon 22k Jan 9, 2023
Repository for data structure and algorithms in Python for coding interviews

Python Data Structures and Algorithms This repository contains questions requiring implementation of data structures and algorithms concepts. It is us

Prabhu Pant 1.9k Jan 1, 2023
Python Sorted Container Types: Sorted List, Sorted Dict, and Sorted Set

Python Sorted Containers Sorted Containers is an Apache2 licensed sorted collections library, written in pure-Python, and fast as C-extensions. Python

Grant Jenks 2.8k Jan 4, 2023
All Algorithms implemented in Python

The Algorithms - Python All algorithms implemented in Python (for education) These implementations are for learning purposes only. Therefore they may

The Algorithms 150.6k Jan 3, 2023
A lightweight, object-oriented finite state machine implementation in Python with many extensions

transitions A lightweight, object-oriented state machine implementation in Python with many extensions. Compatible with Python 2.7+ and 3.0+. Installa

null 4.7k Jan 1, 2023
:computer: Data Structures and Algorithms in Python

Algorithms in Python Implementations of a few algorithms and datastructures for fun and profit! Completed Karatsuba Multiplication Basic Sorting Rabin

Prakhar Srivastav 2.9k Jan 1, 2023
Algorithms implemented in Python

Python Algorithms Library Laurent Luce Description The purpose of this library is to help you with common algorithms like: A* path finding. String Mat

Laurent Luce 264 Dec 6, 2022
A fast python implementation of the SimHash algorithm.

This Python package provides hashing algorithms for computing cohort ids of users based on their browsing history. As such, it may be used to compute cohort ids of users following Google's Federated Learning of Cohorts (FLoC) proposal.

Hybrid Theory 19 Dec 15, 2022
A command line tool for memorizing algorithms in Python by typing them.

Algo Drills A command line tool for memorizing algorithms in Python by typing them. In alpha and things will change. How it works Type out an algorith

Travis Jungroth 43 Dec 2, 2022
A genetic algorithm written in Python for educational purposes.

Genea: A Genetic Algorithm in Python Genea is a Genetic Algorithm written in Python, for educational purposes. I started writing it for fun, while lea

Dom De Felice 20 Jul 6, 2022
Python sample codes for robotics algorithms.

PythonRobotics Python codes for robotics algorithm. Table of Contents What is this? Requirements Documentation How to use Localization Extended Kalman

Atsushi Sakai 17.2k Jan 1, 2023
An implementation of ordered dithering algorithm in python as multimedia course project

One way of minimizing the size of an image is to simply reduce the number of bits you use to represent each pixel.

null 7 Dec 2, 2022
zoofs is a Python library for performing feature selection using an variety of nature inspired wrapper algorithms. The algorithms range from swarm-intelligence to physics based to Evolutionary. It's easy to use ,flexible and powerful tool to reduce your feature size.

zoofs is a Python library for performing feature selection using a variety of nature-inspired wrapper algorithms. The algorithms range from swarm-intelligence to physics-based to Evolutionary. It's easy to use , flexible and powerful tool to reduce your feature size.

Jaswinder Singh 168 Dec 30, 2022
A Python Package for Portfolio Optimization using the Critical Line Algorithm

A Python Package for Portfolio Optimization using the Critical Line Algorithm

null 19 Oct 11, 2022
The DarkRift2 networking framework written in Python 3

DarkRiftPy is Darkrift2 written in Python 3. The implementation is fully compatible with the original version. So you can write a client side on Python that connects to a Darkrift2 server written in C# using the original Darkrift2 library, and vice versa.

Anton Dobryakov 6 May 23, 2022
🧬 Performant Evolutionary Algorithms For Python with Ray support

?? Performant Evolutionary Algorithms For Python with Ray support

Nathan 49 Oct 20, 2022
Genius Square puzzle solver in Python

Genius Square puzzle solver in Python

James 3 Dec 15, 2022