Python meta class and abstract method library with restrictions.

Overview

abcmeta

PyPi version PyPI pyversions PyPI version fury.io PyPI download month

Python meta class and abstract method library with restrictions.

This library provides a restricted way to validate abstract methods. The Python's default abstract method library only validates the methods that exist in the derived classes and nothing else. What this library provides is apart from that validation it provides validations over the method's signature. All you need is to import ABCMeta and abstractmethod from this library.

It works on both annotations and without annotations methods.

Installation

You can install the package by pip:

$ pip install abcmeta

Note: abcmeta supports Python3.6+.

Quick start

from typing import Dict, Text

from abcmeta import ABCMeta, abstractmethod


class Base(ABCMeta):
    @abstractmethod
    def method_2(self, name: Text, age: int) -> Dict[Text, Text]:
        """Abstract method."""

    @abstractmethod
    def method_3(self, name, age):
        """Abstract method."""

class Drived(Base):
    def method_2(self, name: Text, age: int) -> Dict[Text, Text]:
        return {"name": "test"}

    def method_3(self, name, age):
        pass

If you put a different signature, it will raise an error with 'diff' format with hints about what you've missed:

class Drived(Base):
    def method_2(self, name: Text, age: int) -> List[Text]:
        return {"name": "test"}

And it will raise:

Traceback (most recent call last):
  File "/Workspaces/test.py", line 41, in <module>
    class Drived(Base):
  File "/usr/lib/python3.9/abc.py", line 85, in __new__
    cls = super().__new__(mcls, name, bases, namespace, **kwargs)
  File "/abcmeta/__init__.py", line 179, in __init_subclass__
    raise AttributeError(
AttributeError: Signature of the derived method is not the same as parent class:
- method_2(self, name: str, age: int) -> Dict[str, str]
?                                        ^ ^     -----

+ method_2(self, name: str, age: int) -> List[str]
?                                        ^ ^

Derived method expected to return in 'typing.Dict[str, str]' type, but returns 'typing.List[str]'

For different parameter names:

class Drived(Base):
    def method_2(self, username: Text, age: int) -> List[Text]:
        return {"name": "test"}

And it will raise:

Traceback (most recent call last):
  File "/Workspaces/test.py", line 41, in <module>
    class Drived(Base):
  File "/usr/lib/python3.9/abc.py", line 85, in __new__
    cls = super().__new__(mcls, name, bases, namespace, **kwargs)
  File "/abcmeta/__init__.py", line 180, in __init_subclass__
    raise AttributeError(
AttributeError: Signature of the derived method is not the same as parent class:
- method_2(self, name: str, age: int) -> Dict[str, str]
+ method_2(self, username: str, age: int) -> Dict[str, str]
?                ++++

Derived method expected to get name paramter, but gets username

Issue

If you're faced with a problem, please file an issue on Github.

Contribute

You're always welcome to contribute to the project! Please file an issue and send your great PR.

License

Please read the LICENSE file.

You might also like...
Arcpy Tool developed for ArcMap 10.x that checks DVOF points against TDS data and creates an output feature class as well as a check database.

DVOF_check_tool Arcpy Tool developed for ArcMap 10.x that checks DVOF points against TDS data and creates an output feature class as well as a check d

A python package to adjust the bias of probabilistic forecasts/hindcasts using "Mean and Variance Adjustment" method.

Documentation A python package to adjust the bias of probabilistic forecasts/hindcasts using "Mean and Variance Adjustment" method. Read documentation

AHP Calculator - A method for organizing and evaluating complicated decisions, using Maths and Psychology
AHP Calculator - A method for organizing and evaluating complicated decisions, using Maths and Psychology

AHP Calculator - A method for organizing and evaluating complicated decisions, using Maths and Psychology

What Do Deep Nets Learn? Class-wise Patterns Revealed in the Input Space

What Do Deep Nets Learn? Class-wise Patterns Revealed in the Input Space Introduction: Environment: Python3.6.5, PyTorch1.5.0 Dataset: CIFAR-10, Image

Coursework project for DIP class. The goal is to use vision to guide the Dashgo robot through two traffic cones in bright color.

Coursework project for DIP class. The goal is to use vision to guide the Dashgo robot through two traffic cones in bright color.

A class to draw curves expressed as L-System production rules
A class to draw curves expressed as L-System production rules

A class to draw curves expressed as L-System production rules

A simple flashcard app built as a final project for a databases class.

CS2300 Final Project - Flashcard app 'FlashStudy' Tech stack Backend Python (Language) Django (Web framework) SQLite (Database) Frontend HTML/CSS/Java

Final project in KAIST AI class

mmodal_mixer MLP-Mixer based Multi-modal image-text retrieval Image: Original image is cropped with 16 x 16 patch size without overlap. Then, it is re

Toppr Os Auto Class Joiner

Toppr Os Auto Class Joiner Toppr os is a irritating platform to work with especially for students it takes a while and is problematic most of the time

Comments
  • PR: Catch Multiple Errors

    PR: Catch Multiple Errors

    Would you be open to a PR that catches multiple errors and prints them all at once?

    I was thinking that instead of the raise AttributeError(), the errors could be collected and then raised at the end

    https://github.com/mortymacs/abcmeta/blob/4fef29bdc78b52830b9431d93f66cdccee1adf9b/abcmeta/init.py#L157-L187

    Could be modified like this:

    errors = []
    for name, obj in vars(cls.__base__).items():
        ...
        if name not in cls.__dict__:
            errors.append(
                "Derived class '{}' has not implemented '{}' method of the"
                " parent class '{}'.".format(
                    cls.__name__, name, cls.__base__.__name__
                )
            )
            continue
        ...
    if errors:
        raise AttributeError("\n\n".join(errors))
    
    enhancement 
    opened by KyleKing 4
  • feat(#4): collect all errors

    feat(#4): collect all errors

    Fixes #4

    Adds feature and tests for printing multiple errors are once

    > python tests/multiple_incorrect_methods_test.py
    Traceback (most recent call last):
      File "/Users/kyleking/Developer/Pull_Requests/abcmeta/tests/multiple_incorrect_methods_test.py", line 27, in <module>
        class ABCDerived(ABCParent):
      File "/Users/kyleking/.asdf/installs/python/3.10.5/lib/python3.10/abc.py", line 106, in __new__
        cls = super().__new__(mcls, name, bases, namespace, **kwargs)
      File "/Users/kyleking/.asdf/installs/python/3.10.5/lib/python3.10/site-packages/abcmeta/__init__.py", line 192, in __init_subclass__
        raise AttributeError("\n\n".join(errors))
    AttributeError: Derived class 'ABCDerived' has not implemented 'method_1' method of the parent class 'ABCParent'.
    
    Signature of the derived method is not the same as parent class:
    - method_2(self, name: str, age: int) -> Dict[str, str]
    ?                      ^ -
    
    + method_2(self, name: int, age: int) -> Dict[str, str]
    ?                      ^^
    
    Derived method expected to get 'name:<class 'str'>' paramter's type, but gets 'name:<class 'int'>'
    
    Signature of the derived method is not the same as parent class:
    - method_4(self, name: str, age: int) -> Tuple[str, str]
    ?                ^  ^
    
    + method_4(self, family: str, age: int) -> Tuple[str, str]
    ?                ^  ^^^
    
    Derived method expected to get 'name' paramter, but gets 'family'
    

    Only downside is that maybe the join on 2x \n could be more clear. Should it be something involving dashes like '-' * 80 or 3x \n?

    opened by KyleKing 3
  • ci: attempt to fix failing tests

    ci: attempt to fix failing tests

    Testing out a possible fix for CI. Worked locally in zsh. ~~Probably needed to make the step a bash shell~~ (already bash by default), but trying moving them to environment variables first

    Update: ended up restoring the original text that worked before. Can't have nice things

    opened by KyleKing 1
Releases(v2.1.1)
Owner
Morteza NourelahiAlamdari
Senior Software Engineer
Morteza NourelahiAlamdari
Check COVID locations of interest against Google location history

Location of Interest Checker Script to compare COVID locations of interest to Google location history. The script produces a map plot (as shown below)

9 Mar 30, 2022
CHIP-8 interpreter written in Python

chip8py CHIP-8 interpreter written in Python Contents About Installation Usage License About CHIP-8 is an interpreted language developed during the 19

Robert Olaru 1 Nov 09, 2021
pyForgeCert is a Python equivalent of the original ForgeCert written in C#.

pyForgeCert is a Python equivalent of the original ForgeCert written in C#.

Evi1cg 47 Oct 08, 2022
Python program to start your zoom meetings

zoomstarter Python programm to start your zoom meetings More about Initially this was a bash script for starting zoom meetings, but as i started devel

Viktor Cvetanovic 2 Nov 24, 2021
A tool for checking if the external data used in Flatpak manifests is still up to date

Flatpak External Data Checker This is a tool for checking for outdated or broken links of external data in Flatpak manifests. Motivation Flatpak apps

Flathub 76 Dec 24, 2022
With the initiation of the COVID vaccination drive across India for all individuals above the age of 18, I wrote a python script which alerts the user regarding open slots in the vicinity!

cowin_notifier With the initiation of the COVID vaccination drive across India for all individuals above the age of 18, I wrote a python script which

13 Aug 01, 2021
pyshell is a Linux subprocess module

pyshell A Linux subprocess module, An easier way to interact with the Linux shell pyshell should be cross platform but has only been tested with linux

4 Mar 02, 2022
Fix Eitaa Messenger's Font Problem on Linux

Fix Eitaa Messenger's Font Problem on Linux

6 Oct 15, 2022
Repositório do Projeto de Jogo da Resília Educação.

Jogo da Segurança das Indústrias Acme Descrição Este jogo faz parte do projeto de entrega do primeiro módulo da Resilia Educação, referente ao curso d

Márcio Estevam da Silva 2 Apr 28, 2022
A frontend to ease the use of pulseaudio's routing capabilities, mimicking voicemeeter's workflow

Pulsemeeter A frontend to ease the use of pulseaudio's routing capabilities, mimicking voicemeeter's workflow Features Create virtual inputs and outpu

Gabriel Carneiro 164 Jan 04, 2023
A nonebot2 plugin, send news information in a picture form.

A nonebot2 plugin, send news information in a picture form.

幼稚园园长 7 Nov 18, 2022
Decoupled Smoothing in Probabilistic Soft Logic

Decoupled Smoothing in Probabilistic Soft Logic Experiments for "Decoupled Smoothing in Probabilistic Soft Logic". Probabilistic Soft Logic Probabilis

Kushal Shingote 1 Feb 08, 2022
UF3: a python library for generating ultra-fast interatomic potentials

Ultra-Fast Force Fields (UF3) S. R. Xie, M. Rupp, and R. G. Hennig, "Ultra-fast interpretable machine-learning potentials", preprint arXiv:2110.00624

Ultra-Fast Force Fields 24 Nov 13, 2022
Calc.py - A powerful Python REPL calculator

Calc - A powerful Python REPL calculator This is a calculator with a complex sou

Alejandro 8 Oct 22, 2022
A new mini-batch framework for optimal transport in deep generative models, deep domain adaptation, approximate Bayesian computation, color transfer, and gradient flow.

BoMb-OT Python3 implementation of the papers On Transportation of Mini-batches: A Hierarchical Approach and Improving Mini-batch Optimal Transport via

Khai Ba Nguyen 18 Nov 14, 2022
Always fill your package requirements without the user having to do anything! Simple and easy!

WSL Should now work always-fill-reqs-python3 Always fill your package requirements without the user having to do anything! Simple and easy! Supported

Hashm 7 Jan 19, 2022
Esercizi di Python svolti per il biennio di Tecnologie Informatiche.

Esercizi di Python Un piccolo aiuto per Sofia che nel 2° quadrimestre inizierà Python :) Questo repository (termine tecnico di Git) puoi trovare tutti

Leonardo Essam Dei Rossi 2 Nov 07, 2022
This tool don't used illegal ativity

ETHICALTOOL This tool for only educational purposes don't used illegal ativity @onlinehacking this tool for pkg update && pkg upgrade && pkg install g

Mrkarthick 4 Dec 23, 2021
Hacktoberfest 2021 contribution repository✨

🎃 HacktoberFest-2021 🎃 Repository for Hacktoberfest Note: Although, We are actively focusing on Machine Learning, Data Science and Tricky Python pro

Manjunatha Sai Uppu 42 Dec 11, 2022
Arcpy Tool developed for ArcMap 10.x that checks DVOF points against TDS data and creates an output feature class as well as a check database.

DVOF_check_tool Arcpy Tool developed for ArcMap 10.x that checks DVOF points against TDS data and creates an output feature class as well as a check d

3 Apr 18, 2022