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
Scripts to integrate DFIR-IRIS, MISP and TimeSketch

Scripts to integrate DFIR-IRIS, MISP and TimeSketch

Koen Van Impe 20 Dec 16, 2022
lets learn Python language with basic examples. highly recommended for beginners who just start coding.

Lets Learn Python 🐍 Learn python from basic programs. learn python from scratch. 1.Online python compiler: https://www.onlinegdb.com/online_python_co

Subhranshu Choudhury 1 Jan 18, 2022
Button paginator using discord_components

Button Paginator With discord-components Button paginator using discord_components Welcome! It's a paginator for discord-componets! Thanks to the orig

Decave 7 Feb 12, 2022
Snek-test - An operating system kernel made in python and assembly

pythonOS An operating system kernel made in python and assembly Wait what? It us

TechStudent10 2 Jan 25, 2022
SmartGrid - Een poging tot een optimale SmartGrid oplossing, door Dirk Kuiper & Lars Zwaan

SmartGrid - Een poging tot een optimale SmartGrid oplossing, door Dirk Kuiper & Lars Zwaan

1 Jan 12, 2022
Python script to combine the statistical results of a TOPAS simulation that was split up into multiple batches.

topas-merge-simulations Python script to combine the statistical results of a TOPAS simulation that was split up into multiple batches At the top of t

Sebastian Schäfer 1 Aug 16, 2022
Dashboard to view a stock's basic information, RSI, Bollinger bands, EMA, SMA, sentiment analysis via Python

Your One And Only Trading Bot No seriously, we mean it! Contributors Jihad Al-Hussain John Gaffney Shanel Kuchera Kazuki Takehashi Patrick Thornquist

5 May 21, 2022
Tomador de ramos UC automatico para Windows, Linux y macOS

auto-ramos v2.0 Tomador de ramos UC automatico para Windows, Linux y macOS Funcion Este script de Python tiene como principal objetivo hacer que la to

Open Source eUC 13 Jun 29, 2022
A collection of simple tools that proved to be needed for hadling large periodic calculations with the VASP software package.

VESTA-tools A collection of simple tools that proved to be needed for handling large periodic calculations with the VASP software package. distTotCalc

Ilia Kichev 2 Dec 14, 2021
Emulate and Dissect MSF and *other* attacks

Need help in analyzing Windows shellcode or attack coming from Metasploit Framework or Cobalt Strike (or may be also other malicious or obfuscated code)? Do you need to automate tasks with simple scr

123 Dec 16, 2022
importlib_resources is a backport of Python standard library importlib.resources module for older Pythons.

importlib_resources is a backport of Python standard library importlib.resources module for older Pythons. The key goal of this module is to replace p

Python 36 Dec 13, 2022
An Airflow operator to call the main function from the dbt-core Python package

airflow-dbt-python An Airflow operator to call the main function from the dbt-core Python package Motivation Airflow running in a managed environment

Tomás Farías Santana 93 Jan 08, 2023
Repositório contendo atividades no curso de desenvolvimento de sistemas no SENAI

SENAI-DES Este é um repositório contendo as atividades relacionadas ao curso de desenvolvimento de sistemas no SENAI. Se é a primeira vez em contato c

Abe Hidek 4 Dec 06, 2022
Project issue to website data transformation toolkit

braintransform Project issue to website data transformation toolkit. Introduction The purpose of these scripts is to be able to dynamically generate t

Brainhack 1 Nov 19, 2021
It is a Blender Tool which can convert the Object Data Attributes in face corner to the UVs or Vertex Color.

Blender_ObjectDataAttributesConvertTool It is a Blender Tool which can convert the Object Data Attributes in face corner to the UVs or Vertex Color. D

Takeshi Chō 2 Jan 08, 2022
This application is made solely for entertainment purposes

Timepass This application is made solely for entertainment purposes helps you find things to do when you're bored ! tells jokes guaranteed to bring on

Omkar Pramod Hankare 2 Nov 24, 2021
poetry2nix turns Poetry projects into Nix derivations without the need to actually write Nix expressions

poetry2nix poetry2nix turns Poetry projects into Nix derivations without the need to actually write Nix expressions. It does so by parsing pyproject.t

Nix community projects 405 Dec 29, 2022
Mute your mic while you're typing. An app for Ubuntu.

Hushboard Mute your microphone while typing, for Ubuntu. Install from kryogenix.org/code/hushboard/. Installation We recommend you install Hushboard t

Stuart Langridge 142 Jan 05, 2023
A short course on Julia and open-source software development

Advanced Scientific Computing: producing better code This course is taught as a 6-session "nanocourse" at Washington University in St. Louis. See the

Tim Holy 230 Jan 07, 2023
A simple interface to help lazy people like me to shutdown/reboot/sleep their computer remotely.

🦥 Lazy Helper ! A simple interface to help lazy people like me to shut down/reboot/sleep/lock/etc. their computer remotely. - USAGE If you're a lazy

MeHDI Rh 117 Nov 30, 2022