Traits for Python3

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
You might also like...
☘️ Projet Voltaire Solver in Python3
☘️ Projet Voltaire Solver in Python3

☘️ Projet Voltaire Solver in Python3

🏃 Python3 Solutions of All Problems in GKS 2022 (In Progress)

GoogleKickStart 2022 Python3 solutions of Google Kick Start 2022. Solution begins with * means it will get TLE in the largest data set. Total computat

msImpersonate - User account impersonation written in pure Python3
msImpersonate - User account impersonation written in pure Python3

msImpersonate v1.0 msImpersonate is a Python-native user impersonation tool that is capable of impersonating local or network user accounts with valid

python3.5+ hubspot client based on hapipy, but modified to use the newer endpoints and non-legacy python

A python wrapper around HubSpot's APIs, for python 3.5+. Built initially around hapipy, but heavily modified. Check out the documentation here! (thank

🎨 Python3 binding for `@AntV/G2Plot` Plotting Library .
🎨 Python3 binding for `@AntV/G2Plot` Plotting Library .

PyG2Plot 🎨 Python3 binding for @AntV/G2Plot which an interactive and responsive charting library. Based on the grammar of graphics, you can easily ma

Display machine state using Python3 with Flask.
Display machine state using Python3 with Flask.

Flask-State English | 简体中文 Flask-State is a lightweight chart plugin for displaying machine state data in your web application. Monitored Metric: CPU,

A Python3 script to decode an encoded VBScript file, often seen with a .vbe file extension

vbe-decoder.py Decode one or multiple encoded VBScript files, often seen with a .vbe file extension. Usage usage: vbe-decoder.py [-h] [-o output] file

[python3.6] 运用tf实现自然场景文字检测,keras/pytorch实现ctpn+crnn+ctc实现不定长场景文字OCR识别
[python3.6] 运用tf实现自然场景文字检测,keras/pytorch实现ctpn+crnn+ctc实现不定长场景文字OCR识别

本文基于tensorflow、keras/pytorch实现对自然场景的文字检测及端到端的OCR中文文字识别 update20190706 为解决本项目中对数学公式预测的准确性,做了其他的改进和尝试,效果还不错,https://github.com/xiaofengShi/Image2Katex 希

Python3 Interface to numa Linux library

py-libnuma is python3 interface to numa Linux library so that you can set task affinity and memory affinity in python level for your process which can help you to improve your code's performence.

学习 python3 以来写的一些垃圾玩具……

和东哥做兄弟 Author: chiupam 版权 未经本人同意,仓库内所有资源文件,禁止任何公众号、自媒体、开发者进行任何形式的转载、发布、搬运。 声明 这不是一个开源项目,只是把 GitHub 当作一个代码的存储空间,本项目不接受任何开源要求。 仅用于学习研究,禁止用于商业用途,不能保证其合法性

Basic Python3 request wrapper for the PancakeSwap API

🐍 Python Pancakes 🥞 A simple request wrapper for the Pancake-Swap API. Installation Install package # Using pip $ pip install pythonpancakes # Or f

python3 scrip for case conversion of source code files writen in fixed form fortran

convert_FORTRAN_case python3 scrip for case conversion of source code files writen in fixed form fortran python3 scrip for case conversion of source c

a BTC mining program based on python3

BTC-Miner a BTC mining program based on python3 Our project refers to the nightminer project by ricmoo, which is written in Python2 (https://github.co

A Simple, LightWeight, Statically-Typed Python3 API wrapper for GogoAnime.

AniKimi API A Simple, LightWeight, Statically-Typed Python3 API wrapper for GogoAnime The v2 of gogoanimeapi (depreciated) Made with JavaScript and Py

Link aggregator community organised by tags in python3/django3 + sqlite3.
Link aggregator community organised by tags in python3/django3 + sqlite3.

sic Link aggregator community organised by tags in python3/django3 + sqlite3. Public instance at https://sic.pm and Tor hidden service.

QSynthesis is a Python3 API to perform I/O based program synthesis of bitvector expressions.

QSynthesis is a Python3 API to perform I/O based program synthesis of bitvector expressions. It aims at facilitating code deobfuscation. The algorithm is greybox approach combining both a blackbox I/O based synthesis and a whitebox AST search to synthesize sub-expressions

DependConfusion-X Tool is written in Python3 that scans and monitors list of hosts for Dependency Confusion
DependConfusion-X Tool is written in Python3 that scans and monitors list of hosts for Dependency Confusion

DependConfusion-X Tool is written in Python3 which allows security researcher/bug bounty hunter to scan and monitor list of hosts for Dependency Confusion.

HtmlWebShot - A python3 package which Can Create Images From url, Html-CSS, Svg and from any readable file and texts with many setup features.
HtmlWebShot - A python3 package which Can Create Images From url, Html-CSS, Svg and from any readable file and texts with many setup features.

A python3 package which Can Create Images From url, Html-CSS, Svg and from any readable file and texts with many setup features

Vanilla and Prototypical Networks with Random Weights for image classification on Omniglot and mini-ImageNet. Made with Python3.

vanilla-rw-protonets-project Vanilla Prototypical Networks and PNs with Random Weights for image classification on Omniglot and mini-ImageNet. Made wi

Comments
  • Example of how things work in the README

    Example of how things work in the README

    Hi! I think this looks interesting (found on HN), but I'd like to see an example of how PyTraits is used. My suggestion would be to add it to the top of the README, to tell random people like me what this is.

    opened by EmilStenstrom 3
Owner
null
python3 scrip for case conversion of source code files writen in fixed form fortran

convert_FORTRAN_case python3 scrip for case conversion of source code files writen in fixed form fortran python3 scrip for case conversion of source c

null 7 Sep 20, 2022
Rufus port to linux, writed on Python3

Rufus-for-Linux Rufus port to linux, writed on Python3 Программа будет иметь тот же интерфейс что и оригинал, и тот же функционал. Программа создается

null 6 Jan 7, 2022
IEEE ITU bunyesinde komitelere verilen Python3 egitiminin dokumanlastirilmis versiyonlari bu repository altinda tutulmaktadir.

IEEE ITU Python Egitimi Nasil Faydalanmaliyim? Dersleri izledikten sonra dokumanlardaki kodlari yorum satirlari isaretlerini kaldirarak deneyebilirsin

İTÜ IEEE Student Branch 47 Sep 4, 2022
This Python3 script will monitor Upwork RSS feed and then email you the results.

Upwork RSS Parser This Python3 script will monitor Upwork RSS feed and then email you the results. Table of Contents General Info Technologies Used Fe

Chris 5 Nov 29, 2021
Rufus port to linux, writed on Python3

Rufus-for-Linux Rufus port to linux, writed on Python3 Программа будет иметь тот же интерфейс что и оригинал, и тот же функционал. Программа создается

null 10 May 12, 2022
Let’s Play with Python3

Python3-FirstEdition a bunch of python programs and stuff Super Important Notice THIS IS LICENSED UNDER GNU PUBLIC LICENSE V3 also, refer to Contribut

Jym Patel 2 Nov 24, 2022
py-js: python3 objects for max

Simple (and extensible) python3 externals for MaxMSP

Shakeeb Alireza 39 Nov 20, 2022
Advanced IPv4 Subnet Calculator in Python3

Advanced IPv4 Subnet Calculator in Python3 Table of Contents Getting Started Installation How it works? SVI Configuration Template Previews Getting St

Osama Abbas 1 May 10, 2022
An extremely configurable markdown reverser for Python3.

?? Unmarkd A markdown reverser. Unmarkd is a BeautifulSoup-powered Markdown reverser written in Python and for Python. Why This is created as a StackS

ThatXliner 5 Jun 27, 2022
Игра реализована с помощью языке python3.9, библиотеки pygame

Игра в танки Игра реализована с помощью языке python3.9, библиотеки pygame. Игра имеет несколько уровней. Правила: есть танки, которые стреляют, есть

null 1 Jan 1, 2022