Traits for Python3

Related tags

Miscellaneouspytrait
Overview

Find the package here: https://pypi.org/project/pytrait/0.0.2/

PyTrait

Do you like Python, but think that multiple inheritance is a bit too flexible? Are you looking for a more constrained way to define interfaces and re-use code?

Try using PyTraits!

We provide three metaclasses that aid writing code for shared behavior separately from concrete types. For the most part, Traits define interfaces, Structs define state, and Impls define implementation. Traits must be defined before any Impls which implement them, and Impls must be defined before the Structs that use them.

See examples under examples/.

Traits

Traits are abstract base classes (ABCs). There's really not much else to say, except that these ABCs are always implemented in Impl classes, which themselves have no abstract methods, but are not concrete classes; instead an Impl is associated with another type that it bestows implementation upon. This would be either a concrete class (always a Struct) or all such concrete classes implementing a given Trait.

from pytrait import Trait, abstractmethod    

class MyTrait(metaclass=Trait):
    @abstractmethod
    def my_method(self) -> str:
        pass

Structs

Python has dataclasses, and they're great. We're using them internally for our Structs, so whenever you see metaclass=Struct, the class is also a dataclass. Don't get confused with the existing Python module struct -- that one is lower-case.

from pytrait import Struct

class MyStruct(metaclass=Struct):
    my_message: str = "this is a dataclass"

    def __post_init__(self):
        assert my_message == "this is a dataclass"

Impls

Impls bring together Traits and Structs. They represent the implementation details that satisfy one particular interface.

Why isn't the implementation just all together under the Struct? Organization, mostly. Also, "blanket" Impls can provide implementation for any Struct implementing a given Trait, so Impls allow for greater code re-use.

Impls have to indicate which Structs they bestow implementation upon. You can follow a strict naming convention, like ImplMyTraitForMyStruct. This is sufficient. Or, you can use any name you want so long as you also provide a keyword argument target="StructName" alongside the metaclass argument.

from pytrait import Impl

class MyImpl(MyTrait, metaclass=Impl, target="MyStruct"):
    ...

This is used to automate the list of implementations for MyStruct; you don't need to explicitly list any superclasses of MyStruct, just based on the Impl name it will inherit from all relevant Impls.

FAQ

This reminds me of another programming language

That is not a question, but you have indeed figured me out. This way of organizing Python code was heavily inspired by the Rust programming language. But beyond being an imitation, it's a testament to how powerful Python is. My philosophy is that if you're not using the flexibility of Python to limit yourself, you're not making use of the full flexibility of Python.

What doesn't work?

A Struct can't have traits with overlapping method names. Rust can solve this with its "fully qualified syntax", or by type constraints, but Python will by default only resolve to the method from the first listed superclass (see Python's "Method Resolution Order").

I don't think there's any easy way around this, because in Python there's no clear way to choose which implementation to use based on type annotation. If you really want to let a Struct implement two traits that have the same method name, you can always wrap your class definition in a try block and catch the MultipleImplementationError. Maybe you can find a way to make it work.

TODO

  • Supertraits
  • better README
Bitflip Fault Simulation Platform by Daniele Rizzieri (2021)

BFSP [v1.05] Bitflip Fault Simulation Platform by Daniele Rizzieri (2021) The platform injects a random bitflip in each of N copies of a binary file.

Daniele Rizzieri 2 Nov 05, 2022
Um Script De Mensagem anonimas Para linux e Termux Feito em python

Um Script De Mensagem anonimas Para linux e Termux Feito em python feito em um celular

6 Sep 09, 2021
Paxos in Python, tested with Jepsen

Python implementation of Multi-Paxos with a stable leader and reconfiguration, roughly following "Paxos Made Moderately Complex". Run python3 paxos/st

A. Jesse Jiryu Davis 25 Dec 15, 2022
Let's pretend you want to create a AWS Lambda project called "sns-processor".

Usage Let's pretend you want to create a AWS Lambda project called "sns-processor". Rather than using lambda and then editing the results to include y

1 Dec 31, 2021
Generalise Prometheus metrics. takes out server specific, replaces variables and such.

Generalise Prometheus metrics. takes out server specific, replaces variables and such. makes it easier to copy from Prometheus console straight to Grafana.

ziv 5 Mar 28, 2022
Minimalistic Gridworld Environment (MiniGrid)

Minimalistic Gridworld Environment (MiniGrid) There are other gridworld Gym environments out there, but this one is designed to be particularly simple

Maxime Chevalier-Boisvert 1.7k Jan 03, 2023
Quick script for automatically extracting syscall numbers for an OS

Syscalls-Extractor Quick script for automatically extracting syscall numbers for an OS $ python3 .\syscalls-extractor.py --help usage: syscalls-extrac

m0rv4i 54 Feb 10, 2022
peace-performance (Rust) binding for python. To calculate star ratings and performance points for all osu! gamemodes

peace-performance-python Fast, To calculate star ratings and performance points for all osu! gamemodes peace-performance (Rust) binding for python bas

9 Sep 19, 2022
Dot Browser is a privacy-conscious web browser with smarts built-in for protection against trackers and advertisments online.

🌍 Take back your privacy with Dot Browser, the privacy-conscious web browser that protects you from being tracked and monitored online.

Dot HQ 1k Jan 07, 2023
Explore related sequences in the OEIS

OEIS explorer This is a tool for exploring two different kinds of relationships between sequences in the OEIS: mentions (links) of other sequences on

Alex Hall 6 Mar 15, 2022
Refer'd Resume Scanner

Refer'd Resume Scanner I wanted to share a free resource we built to assist applicants with resume building. Our resume scanner identifies potential s

Refer'd 74 Mar 07, 2022
Fixes your Microphone Level to one specific value.

MicLeveler Fixes your Microphone Level to one specific value. Intention A friend of mine has the problem that some programs are setting his microphone

Moritz Timpe 2 Oct 14, 2021
奇遇淘客服务器端

奇遇淘客 APP 服务器端 警告 正在使用 v0.2.0 版本的用户,请尽快升级到 v0.2.1。 v0.2.0 版本的 Docker 镜像中包含了有问题的 aiohttp。 奇遇淘客代码库 奇遇淘客 iOS APP 奇遇淘客 Android APP 奇遇淘客文档 服务器端文档 Docker 使用

奇遇科技 92 Nov 09, 2022
The-White-Noise-Project - The project creates noise intentionally

The-White-Noise-Project High quality audio matters everywhere, even in noise. Be

Ali Hakim Taşkıran 1 Jan 02, 2022
Subcert is an subdomain enumeration tool, that finds all the subdomains from certificate transparency logs.

Subcert Subcert is a subdomain enumeration tool, that finds all the valid subdomains from certificate transparency logs. Table of contents Setup Demo

A3h1nt 59 Dec 16, 2022
Lookup for interesting stuff in SMB shares

SMBSR - what is that? Well, SMBSR is a python script which given a CIDR/IP/IP_file/HOSTNAME(s) enumerates all the SMB services listening (445) among t

Vincenzo 112 Dec 15, 2022
A webapp that timestamps key moments in a football clip

A look into what we're building Demo.mp4 Prerequisites Python 3 Node v16+ Steps to run Create a virtual environment. Activate the virtual environment.

Pranav 1 Dec 10, 2021
Supercharge your NFTs with new behaviours and superpowers!

WrapX Supercharge your NFTs with new behaviours and superpowers! WrapX is a collection of Wrappers (currently one - WrapXSet) to decorate your NTFs ad

Emiliano Bonassi 9 Jun 13, 2022
CaskDB is a disk-based, embedded, persistent, key-value store based on the Riak's bitcask paper, written in Python.

CaskDB - Disk based Log Structured Hash Table Store CaskDB is a disk-based, embedded, persistent, key-value store based on the Riak's bitcask paper, w

886 Dec 27, 2022
From "fixed RAnDom CRashes" to "[FIX] Fixed random crashes."

Clean Commit From fixed RAnDom CRashes to [FIX] Fixed random crashes. Clean commit helps you by auto-formating your commits to make your repos better

Mathias 3 Dec 26, 2021