GithubHelp home page GithubHelp logo

kiwnix / persisting-theory Goto Github PK

View Code? Open in Web Editor NEW
0.0 0.0 2.0 26 KB

Clone of https://code.agate.blue/agate/persisting-theory

License: BSD 3-Clause "New" or "Revised" License

Python 100.00%

persisting-theory's Introduction

Introduction

For more details about what kind of problems this package tries to solve, please refer to http://next.kii.eliotberriot.com/stream/eliotberriot/items/25.

Persisting-theory is a small python utility designed to automate data discovering and access inside a list of packages. Use case: you are building an application that will have pluggable components. You want to allow these components to register data so it can be accessed by any other component of your app. If you ever used Django framework, you may remember this:

from django.contrib import admin
admin.autodiscover()

Basically, persisting-theory will do the same, except that it let you declare what you want to autodiscover.

Okay, I'm bad at explaining things, and english is not my mother tongue. Let's build a simple example.

Quickstart

Install

Install the package from PyPi. via pip (or any other tool):

pip install persisting-theory

Persisting-theory does not require any dependency but a python installation (it has been tested on python 2.7 and python 3.4).

Setup

A basic setup:

# registries.py

from persiting_theory import Registry

class CallbacksRegistry(Registry):
    """
        Allow your apps to register callbacks
    """
    # the package where the registry will try to find callbacks in each app
    look_into = "callbacks_registry"

callbacks_registry = CallbacksRegistry()


# app1/callbacks_registry.py

from registries import callbacks_registry

@callbacks_registry.register
def dog():
    print("Wouf")


# app2/callbacks_registry.py

from registries import callbacks_registry

@callbacks_registry.register
def cat():
    print("Meow")


# dosomething.py

from registries import callbacks_registry

APPS = (
    'app1',
    'app2',
)

# Trigger autodiscovering process
callbacks_registry.autodiscover(APPS)

for callback in callbacks_registry.values():
    callback()

    # Wouf
    # Meow

API

Registry inherits from python built-in collections.OrderedDict, which means you can use regular dict methods to access registered data:

callbacks_registry.get("dog")()  #  will print Wouf
assert callbacks_registry.get("chicken", None) is None

Registry.register()

You can use this function as a decorator for registering functions and classes:

from persisting_theory import Registry

class AwesomeRegistry(Registry):
    pass

r = AwesomeRegistry()

# register a class
@r.register
class AwesomeClass:
    pass

# register a function
@r.register
def awesome_function():
    pass

# By default, the key in the registry for a given value is obtained from the function or class name, if possible

assert r.get("AwesomeClass") == AwesomeClass
assert r.get("awesome_function") == awesome_function

# You can override this behaviour:

@r.register(name="Chuck")
class AwesomeClass:
    pass

@r.register(name="Norris")
def awesome_function():
    pass

assert r.get("Chuck") == AwesomeClass
assert r.get("Norris") == awesome_function


# You can also use the register method as is

awesome_var = "Chuck Norris"
r.register(awesome_var, name="Who am I ?")

assert r.get("Who am I ?") == awesome_var

# I f you are not registering a function or a class, you MUST provide a name argument

Registry.validate()

By default, a registry will accept any registered value. Sometimes, it's not what you want, so you can restrict what kind of data your registry accepts:

from persisting_theory import Registry

class StartsWithAwesomeRegistry(Registry):

    def validate(self, data):
        if isinstance(data, str):
            return data.startswith("awesome")
        return False

r = StartsWithAwesomeRegistry()

# will pass registration
r.register("awesome day", name="awesome_day")

# will fail and raise ValueError
r.register("not so awesome day", name="not_so_awesome_day")

Registry.prepare_data()

If you want to manipulate your data before registering it, override this method. In this example, we prefix every registered string with 'hello':

from persisting_theory import Registry

class HelloRegistry(Registry):

    def prepare_data(self, data):
        return 'hello ' + data

r = HelloRegistry()

class Greeting:
    def __init__(self, first_name):
        self.first_name = first_name


r.register(Greeting('World'), name="world")
r.register(Greeting('Eliot'), name="eliot")

assert r.register.get('world') == "hello World"
assert r.register.get('eliot') == "hello Eliot"

Registry.prepare_name()

In a similar way, you can manipulate the name of registered data. This can help if you want to avoid repetitions. Let's improve our previous example:

from persisting_theory import Registry

class HelloRegistry(Registry):

    def prepare_data(self, data):
        return 'hello ' + data

    def prepare_name(self, data, name=None):
        return self.data.first_name.lower()

r = HelloRegistry()

class Greeting:
    def __init__(self, first_name):
        self.first_name = first_name


r.register(Greeting('World'))
r.register(Greeting('Eliot'))

assert r.register.get('world') == "hello World"
assert r.register.get('eliot') == "hello Eliot"

Going meta

If you have multiple registries, or want to allow your apps to declare their own registries, this is for you:

# registries.py

from persisting_theory import meta_registry, Registry

class RegistryA(Registry):
    look_into = "a"

class RegistryB(Registry):
    look_into = "b"

registry_a = RegistryA()
meta_registry.register(registry_a, name="registry_a")

registry_b = RegistryB()
meta_registry.register(registry_b, name="registry_b")


# dosomethingelse.py

from persisting_theory import meta_registry

# will import registries declared in `registries` packages, and trigger autodiscover() on each of them
meta_registry.autodiscover(apps=("app1", "app2"))

What the hell is that name ?

It's an anagram for "python registries".

Contribute

Contributions, bug reports, and "thank you" are welcomed. Feel free to contact me at <[email protected]>.

License

The project is licensed under BSD licence.

persisting-theory's People

Contributors

eliotberriot avatar kiwnix avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.