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
NYCU(NCTU)-差勤-助教

NCTU-TA-fill 填寫 差勤-助教時數 有沒有覺得在差勤系統填助教時數有點浪費生命? 今天有個懶鬼浪費好多時間幫大家寫了code 只要填好的必要的資料,就可以讓電腦自動幫你完成差勤助教的時數填寫喔! https://pt-attendance.nctu.edu.tw/verify/userL

14 Dec 21, 2021
EloGGs 🎮 is a 1v1.LOL Trophy Boosting Program (PATCHED)

EloGGs 🎮 is an old patched 1v1.LOL boosting program I developed months ago, My team made around $1000 total off of this, but now it's been patched by the developers.

doop 1 Jul 22, 2022
Python Interactive Graphical System made during Computer Graphics classes (INE5420-2021.1)

PY-IGS - The PYthon Interactive Graphical System The PY-IGS Installation To install this software you will need these dependencies (with their thevelo

Enzo Coelho Albornoz 4 Dec 03, 2021
DeDRM tools for ebooks

DeDRM_tools DeDRM tools for ebooks This is a fork of Apprentice Harper's version of the DeDRM tools. I've added some of the PRs that still haven't bee

2 Jan 10, 2022
Swubcase - The shitty programming language

What is Swubcase? Swubcase is easy-to-use programming language that can fuck you

5 Jun 19, 2022
Student Enrollment Analysis System

SEAS Student Enrollment Analysis System Steps to start working: create a user name "seas", host name: local, password: seas, mark all checkbox - go C

Md. Zakaria Kabir 3 Jul 12, 2022
Boamp-extractor - Script d'extraction des AOs publiés au BOAMP

BOAMP Extractor BOAMP-Extractor permet d'extraire les offres de marchés publics publiées au bulletin officiel des annonces des marchés publics (BOAMP)

Julien 3 Dec 09, 2022
Woltcheck - Python script to check if a wolt restaurant is ready to deliver to your location

woltcheck Python script to check if a wolt restaurant is ready to deliver to you

30 Sep 13, 2022
This is the accompanying repository for the Bloomberg Global Coal Countdown website.

This is the accompanying repository for the Bloomberg Global Coal Countdown (BGCC) website. Data Sources Dashboard Data Schema and Validation License

7 Jun 01, 2022
Procedural 3D data generation pipeline for architecture

Synthetic Dataset Generator Authors: Stanislava Fedorova Alberto Tono Meher Shashwat Nigam Jiayao Zhang Amirhossein Ahmadnia Cecilia bolognesi Dominik

Computational Design Institute 49 Nov 25, 2022
The parser of a timetable of tennis matches for Flashscore website

FlashscoreParser The parser of a timetable of tennis matches for Flashscore website. The program collects the schedule of tennis matches for two days

Valendovsky 1 Jul 15, 2022
LINUX-AOS (Automatic Optimization System)

LINUX-AOS (Automatic Optimization System)

1 Jul 12, 2022
This python code will get requests from SET (The Stock Exchange of Thailand) a previously-close stock price and return it in Thai Baht currency using beautiful soup 4 HTML scrapper.

This python code will get requests from SET (The Stock Exchange of Thailand) a previously-close stock price and return it in Thai Baht currency using beautiful soup 4 HTML scrapper.

Andre 1 Oct 24, 2022
Some scripts for the Reverse engineered (old) api of CafeBazaar

bazz Note: This project is done and published only for educational purposes. Some scripts for the Reverse engineered (old) API of CafeBazaar. Be aware

Mohsen Tahmasebi 35 Dec 25, 2022
Web interface for browsing, search and filtering recent arxiv submissions

Web interface for browsing, search and filtering recent arxiv submissions

Andrej 4.8k Jan 08, 2023
Python script which allows for automatic registration in Golfbox

Python script which allows for automatic registration in Golfbox

Guðni Þór Björnsson 8 Dec 04, 2021
About A python based Apple Quicktime protocol,you can record audio and video from real iOS devices

介绍 本应用程序使用 python 实现,可以通过 USB 连接 iOS 设备进行屏幕共享 高帧率(30〜60fps) 高画质 低延迟(200ms) 非侵入性 支持多设备并行 Mac OSX 安装 python =3.7 brew install libusb pkg-config 如需使用 g

YueC 124 Nov 30, 2022
Would upload anything I do with/related to brainfuck

My Brainfu*k Repo Basically wanted to create something with Brainfu*k but realized that with the smol brain I have, I need to see the cell values real

Rafeed 1 Mar 22, 2022
Pytorch implementation of "Peer Loss Functions: Learning from Noisy Labels without Knowing Noise Rates"

Peer Loss functions This repository is the (Multi-Class & Deep Learning) Pytorch implementation of "Peer Loss Functions: Learning from Noisy Labels wi

Kushal Shingote 1 Feb 08, 2022