Skip to main content

Simple way to prevent direct creation of an instance of a class.

Project description

Simple Python Factory pattern

PyPI package PyPI version

This module provides a simple way to prevent the direct creation of an instance of a class. Instead a classmethod of this class can be used.

Install

You can install this python module via pip:

pip install simple-factory-pattern

Otherwise the module can be downloaded from PyPI: https://pypi.org/project/simple-factory-pattern/

Usage

  1. Import the module:

    from simple_factory_pattern import FactoryPatternMeta
    
  2. Create a class that uses the above meta class:

    class NewClass(metaclass=FactoryPatternMeta):
        pass
    
  3. Add a classmethod to the new class that returns an instance of the class:

    @classmethod
    def create_instance(cls):
        return NewClass()
    

    You can choose any name for the method. But it must be a classmethod!

    It's also possible to define multiple classmethods. Only in those methods a new instance of the class can be created.

Behavior of the new class

It's not possible to create an instance of the class directly:

instance = NewClass()  # this will fail

This throws a FactoryException (also included in the simple_factory_pattern package).

The only way to get an instance is to call the above definded classmethod:

instance = NewClass.create_instance()  # this works

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

simple_factory_pattern-2.0.0.tar.gz (14.7 kB view hashes)

Uploaded Source

Built Distribution

simple_factory_pattern-2.0.0-py3-none-any.whl (15.7 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page