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
My HA controller for veg and flower rooms

HAGrowRoom My HA controller for veg and flower rooms I will do my best to keep this updated as I change, add and improve. System heavily uses custom t

4 May 25, 2022
vFuzzer is a tool developed for fuzzing buffer overflows, For now, It can be used for fuzzing plain vanilla stack based buffer overflows

vFuzzer vFuzzer is a tool developed for fuzzing buffer overflows, For now, It can be used for fuzzing plain vanilla stack based buffer overflows, The

Vedant Bhalgama 5 Nov 12, 2022
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

16 Aug 08, 2022
A deployer and package manager for OceanBase open-source software.

OceanBase Deploy OceanBase Deploy (简称 OBD)是 OceanBase 开源软件的安装部署工具。OBD 同时也是包管理器,可以用来管理 OceanBase 所有的开源软件。本文介绍如何安装 OBD、使用 OBD 和 OBD 的命令。 安装 OBD 您可以使用以下方

OceanBase 59 Dec 27, 2022
Awesome open-source alternatives to SaaS

Awesome-oss-alternatives - Awesome list of open-source startup alternatives to well-known SaaS products

Runa Capital 12.7k Jan 03, 2023
An Agora Python Flask token generation server

A Flask Starter Application with Login and Registration About A token generation Server using the factory pattern and Blueprints. A forked stripped do

Nii Ayi 1 Jan 21, 2022
A simple app that helps to train quick calculations.

qtcounter A simple app that helps to train quick calculations. Usage Manual Clone the repo in a folder using git clone https://github.com/Froloket64/q

0 Nov 27, 2021
Performance data for WASM SIMD instructions.

WASM SIMD Data This repository contains code and data which can be used to generate a JSON file containing information about the WASM SIMD proposal. F

Evan Nemerson 5 Jul 24, 2022
A program that analyzes data from inertia measurement units installeed in aircraft and generates g-exceedance curves

A program that analyzes data from inertia measurement units installeed in aircraft and generates g-exceedance curves

Pooya 1 Nov 23, 2021
PIP Manager written in python Tkinter

PIP Manager About PIP Manager is designed to make Python Package handling easier by just a click of a button!! Available Features Installing packages

Will Payne 9 Dec 09, 2022
Taichi is a parallel programming language for high-performance numerical computations.

Taichi is a parallel programming language for high-performance numerical computations.

Taichi Developers 22k Jan 04, 2023
The Open edX platform, the software that powers edX!

This is the core repository of the Open edX software. It includes the LMS (student-facing, delivering courseware), and Studio (course authoring) compo

edX 6.2k Jan 01, 2023
uMap lets you create maps with OpenStreetMap layers in a minute and embed them in your site.

uMap project About uMap lets you create maps with OpenStreetMap layers in a minute and embed them in your site. Because we think that the more OSM wil

771 Dec 29, 2022
Shared utility scripts for AI for Earth projects and team members

Overview Shared utilities developed by the Microsoft AI for Earth team The general convention in this repo is that users who want to consume these uti

Microsoft 38 Dec 30, 2022
Python - Aprendendo Python na ByLearn

PYTHON Identação Escopo Pai Escopo filho Escopo neto Variaveis

Italo Rafael 3 May 31, 2022
Integration between the awesome window manager and the firefox web browser.

Integration between the awesome window manager and the firefox web browser.

contribuewwt 3 Feb 02, 2022
DSG - Source code for Digital Scholarship Grant project.

DSG Source code for Dr. Stephanie Tsang's Digital Scholarship Grant project. Work performed by Mr. Wang Minghao while as her Research Assistant. The s

1 Jan 04, 2022
PDX Code Guild Full Stack Python Bootcamp starting 2022/02/28

Class Liger Rough Timeline Weeks 1, 2, 3, 4: Python Weeks 5, 6, 7, 8: HTML/CSS/Flask Weeks 9, 10, 11: Javascript Weeks 12, 13, 14, 15: Django Weeks 16

PDX Code Guild 5 Jul 05, 2022
For radiometrically calibrating and PSF deconvolving IRIS data

irispreppy For radiometrically calibrating and PSF deconvolving IRIS data. I dislike how I need to own proprietary software (IDL) just to simply prepa

Aaron W. Peat 4 Nov 01, 2022
Basic repository showing how to use Hydra + Hydra launchers on SLURM cluster

Slurm-Hydra-Submitit This repository is a minimal working example on how to: setup Hydra setup batch of slurm jobs on top of Hydra via submitit-launch

Raphael Meudec 2 Jul 25, 2022