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
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
A Tool to validate domestic New Zealand vaccine passes

Vaccine Validator Tool to validate domestic New Zealand vaccine passes Create a new virtual environment: python3 -m venv ./venv Activate virtual envi

8 May 01, 2022
Automation of VASP DFT workflows with ASE - application scripts

This repo contains a library that aims at automatizing some Density Functional Theory (DFT) workflows in VASP by using the ASE toolkit.

Frank Niessen 5 Sep 06, 2022
Python AVL Protocols Server for Codec 8 and Codec 8 Extended Protocols

pycodecs Package provides python AVL Protocols Server for Codec 8 and Codec 8 Extended Protocols This package will parse the AVL Data and log it in hu

Vardharajulu K N 2 Jun 21, 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
Extremely unfinished animation toolset for Blender 3.

AbraTools Alpha IMPORTANT: Code is a mess. Be careful using it in production. Bug reports, feature requests and PRs are appreciated. Download AbraTool

Abra 15 Dec 17, 2022
Bitflip Fault Simulation Platform by Daniele Rizzieri (2021)

SEE Injection Framework 2021 This repository contains two Single Event Effect (SEE) injection platforms. The first one is called BFSP - "Bitflip Fault

Daniele Rizzieri 2 Nov 05, 2022
BlackMamba is a multi client C2/post exploitation framework

BlackMamba is a multi client C2/post exploitation framework with some spyware features. Powered by Python 3.8.6 and QT Framework.

Gustavo 873 Dec 29, 2022
原神抽卡记录导出

原神抽卡记录导出 抽卡记录分析工具 from @笑沐泽 抽卡记录导出工具js版,含油猴脚本可在浏览器导出 注意:我的是python版,带饼图的是隔壁electron版,功能类似 Wik

834 Jan 04, 2023
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
This repository is an archive of emails that are sent by the awesome Quincy Larson every week.

Awesome Quincy Larson Email Archive This repository is an archive of emails that are sent by the awesome Quincy Larson every week. If you fi

Sourabh Joshi 912 Jan 05, 2023
Compress .dds file in ggpk to boost fps. This is a python rewrite of PoeTexureResizer.

PoeBooster Compress .dds file in ggpk to boost fps. This is a python rewrite of PoeTexureResizer. Setup Install ImageMagick-7.1.0. Download and unzip

3 Sep 30, 2022
Calculate the efficient frontier

关于 代码主要参考Fábio Neves的文章,你可以在他的文章中找到一些细节性的解释

Wyman Lin 104 Nov 11, 2022
Module 2's katas from Launch X's python introduction course.

Module2Katas Module 2's katas from Launch X's python introduction course. Virtual environment creation process (on Windows): Create a folder in any de

Javier Méndez 1 Feb 10, 2022
List of short Codeforces problems with a statement of 1000 characters or less. Python script and data files included.

Shortest problems on Codeforces List of Codeforces problems with a short problem statement of 1000 characters or less. Sorted for each rating level. B

32 Dec 24, 2022
A small script I made that takes any standard Decklist of magic the gathering cards and pulls all card images from scryfall at once!

A small script I made that takes any standard Decklist of magic the gathering cards and pulls all card images from scryfall at once!

15 Aug 26, 2022
Git Hooks Tutorial.

Git Hooks Tutorial My public talk about this project at Sberloga: Git Hooks Is All You Need 1. Git Hooks 101 Init git repo: mkdir git_repo cd git_repo

Dani El-Ayyass 17 Oct 12, 2022
Tiling manager which runs on top of EWMH window managers.

PyTyle is an extremely versatile and extensible tiling manager that is meant to be used on top of EWMH window managers. Its feature set was modeled af

55 Jul 29, 2021
The program calculates the BMI of people

Programmieren Einleitung: Das Programm berechnet den BMI von Menschen. Es ist sehr einfach zu handhaben, so können alle Menschen ihren BMI berechnen.

2 Dec 16, 2021
VHDL to Discrete Logic on PCB Flow

PCBFlow Highly experimental set of scripts to transform a digital circuit described in a hardware description language (VHDL or Verilog) into a discre

Tim 77 Nov 04, 2022