Allows you to canibalize methods from classes effectively implementing trait-oriented programming

Overview

About

This package enables code reuse in non-inheritance way from existing classes, effectively implementing traits-oriented programming pattern.

Story

Once upon a time there was

class AHealthyClass:
    def see(self):
        print('I can see')

    def walk(self):
        print('Walking around')

    def run(self):
        print('I can run')

and he decided to visit his grandma and bring her fresh-baked pie.

But little did he know there was couple of hungry zombies in his merry way waiting to chew on some bones.

They were old decrepit zombies - not very fast nor particulary perseptive.

from canibalize import infect

@infect
class Zombie1:
    def see():
        raise Exception('Arrgh') # he was a pirate, probably

@infect
class Zombie2:
    def walk():
        raise Exception("I've fallen and I can't get up!")

He walked closer and closer to the ambush and then zombies pounced at him. And started eating him.

Zombie1.nomnom(AHealthyClass, 'see')
Zombie2.nomnom(AHealthyClass, ['see', 'walk'])

And then strange things started to happend. Zombie1 who took AHealthyClass eye, start seeing things. And both of them been munching on AHealthyClass legs gain ability of walking again!

z1 = Zombie1()
z1.see()
>>> I can see

z2 = Zombie2()
z2.walk()
>>> Walking around

z1.walk()
>>> Walking around

The miracle is that AHealthyClass can still see and walk and even run. Maybe he was a spider in disguise.

h1 = AHealthyClass()
h1.see()
>>> I can see

h1.walk()
>>> Walking around

And then they took each other's arms(who still had an arm) and walk()-ed into a sunset, which was beutiful to see().

And live happily ever after.

And married each other, probably...

The END

Seriously, though

Lets imagine you have some Library and some Code that uses that Library. You have no controll of both of them, but you need to add/modify functionality to them.

For example, you add serialization/deserialization/validation/schema-generation to classes of that Library, for example with pydantic.

You cannot subclass from Library classes, because Code will not utilize them(without rewriting it ofcause). The only real option you have is to write facade for every class of the Library to add desired behaviour.

With canibalize you can extend Library becaviour without modifying nither Library nor Code.

from Libray import SomeClass
from Code import run

from canibalize import canibalize
from pydantic import BaseModel
from typing import List

class SomeSerialization:
    @classmethod
    def __get_validators__(cls):
        some_class_json_validators = [
            ... SomeClass specific validators
        ]
        for v in some_class_json_validators:
            yield v

    @classmethod
    def __modify_schema__(cls, field_schema):
        field_schema.update(
            ... # update schema based on cls logic
        )


canibalize(
    SomeClass,
    SomeSerialization, 
    ['__get_validators__', __modify_schema__', 'Config']
)

@dataclass
class ResultClass(BaseModel):
    results: List[SomeType]

some = SomeClass(result = [run(*v) for v in mah_values])

# now SomeClass correctly produces json_schema no matter how deep it nested
print(some.json_schema(indent=2)) 
You might also like...
This script allows you to retrieve all functions / variables names of a Python code, and the variables values.

Memory Extractor This script allows you to retrieve all functions / variables names of a Python code, and the variables values. How to use it ? The si

Factoral Methods using two different method

Factoral-Methods-using-two-different-method Here, I am finding the factorial of a number by using two different method. The first method is by using f

Creating low-level foundations and abstractions for asynchronous programming in Python.

DIY Async I/O Creating low-level foundations and abstractions for asynchronous programming in Python (i.e., implementing concurrency without using thr

JavaScript-style async programming for Python.

promisio JavaScript-style async programming for Python. Examples Create a promise-based async function using the promisify decorator. It works on both

A fixture that allows runtime xfail

pytest-runtime-xfail pytest plugin, providing a runtime_xfail fixture, which is callable as runtime_xfail(), to allow runtime decisions to mark a test

Utility to play with ADCS, allows to request tickets and collect information about related objects.

certi Utility to play with ADCS, allows to request tickets and collect information about related objects. Basically, it's the impacket copy of Certify

Package that allows for validate and sanitize of string values.

py.validator A library of string validators and sanitizers Insipired by validator.js Strings only This library validates and sanitizes strings only. P

Pampy: The Pattern Matching for Python you always dreamed of.
Pampy: The Pattern Matching for Python you always dreamed of.

Pampy: Pattern Matching for Python Pampy is pretty small (150 lines), reasonably fast, and often makes your code more readable and hence easier to rea

Basic loader is a small tool that will help you generating Cloudflare cookies

Basic Loader Cloudflare cookies loader This tool may help some people getting valide cloudflare cookies Installation 🔌 : pip install -r requirements.

Owner
null
Pyfunctools is a module that provides functions, methods and classes that help in the creation of projects in python

Pyfunctools Pyfunctools is a module that provides functions, methods and classes that help in the creation of projects in python, bringing functional

Natanael dos Santos Feitosa 5 Dec 22, 2022
A Python package implementing various colour checker detection algorithms and related utilities.

A Python package implementing various colour checker detection algorithms and related utilities.

colour-science 147 Dec 29, 2022
Implementing C++ Semantics in Python

Implementing C++ Semantics in Python

Tamir Bahar 7 May 18, 2022
Python Classes Without Boilerplate

attrs is the Python package that will bring back the joy of writing classes by relieving you from the drudgery of implementing object protocols (aka d

The attrs Cabal 4.6k Jan 6, 2023
pydsinternals - A Python native library containing necessary classes, functions and structures to interact with Windows Active Directory.

pydsinternals - Directory Services Internals Library A Python native library containing necessary classes, functions and structures to interact with W

Podalirius 36 Dec 14, 2022
A python package containing all the basic functions and classes for python. From simple addition to advanced file encryption.

A python package containing all the basic functions and classes for python. From simple addition to advanced file encryption.

PyBash 11 May 22, 2022
A simple python script to generate an iCalendar file for the university classes.

iCal Generator This is a simple python script to generate an iCalendar file for the university classes. Installation Clone the repository git clone ht

Foad Rashidi 2 Sep 1, 2022
Cleaning-utils - a collection of small Python functions and classes which make cleaning pipelines shorter and easier

cleaning-utils [] [] [] cleaning-utils is a collection of small Python functions

null 4 Aug 31, 2022
Keval allows you to call arbitrary Windows kernel-mode functions from user mode, even (and primarily) on another machine.

Keval Keval allows you to call arbitrary Windows kernel-mode functions from user mode, even (and primarily) on another machine. The user mode portion

null 42 Dec 17, 2022
This is a package that allows you to create a key-value vault for storing variables in a global context

This is a package that allows you to create a key-value vault for storing variables in a global context. It allows you to set up a keyring with pre-defined constants which act as keys for the vault. These constants are then what is stored inside the vault. A key is just a string, but the value that the key is mapped to can be assigned to any type of object in Python. If the object is serializable (like a list or a dict), it can also be writen to a JSON file You can then use a decorator to annotate functions that you want to have use this vault to either store return variables in or to extract variables to be used as input for the function.

Data Ductus 2 Dec 14, 2022