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
This library attempts to abstract the handling of Sigma rules in Python

This library attempts to abstract the handling of Sigma rules in Python. The rules are parsed using a schema defined with pydantic, and can be easily loaded from YAML files into a structured Python object.

Caleb Stewart 44 Oct 29, 2022
VAST - Visualise Abstract Syntax Trees for Python

VAST VAST - Visualise Abstract Syntax Trees for Python. VAST generates ASTs for a given Python script and builds visualisations of them. Install Insta

Jesse Phillips 2 Feb 18, 2022
Tracking development of the Class Schedule Siri Shortcut, an iOS program that checks the type of school day and tells you class scheduling.

Class Schedule Shortcut Tracking development of the Class Schedule Siri Shortcut, an iOS program that checks the type of school day and tells you clas

null 3 Jun 28, 2022
Cross-platform MachO/ObjC Static binary analysis tool & library. class-dump + otool + lipo + more

ktool Static Mach-O binary metadata analysis tool / information dumper pip3 install k2l Development is currently taking place on the @python3.10 branc

Kritanta 301 Dec 28, 2022
Implements a polyglot REPL which supports multiple languages and shared meta-object protocol scope between REPLs.

MetaCall Polyglot REPL Description This repository implements a Polyglot REPL which shares the state of the meta-object protocol between the REPLs. Us

MetaCall 10 Dec 28, 2022
Advanced python code - For students in my advanced python class

advanced_python_code For students in my advanced python class Week Topic Recordi

Ariel Avshalom 3 May 27, 2022
MiniJVM is simple java virtual machine written by python language, it can load class file from file system and run it.

MiniJVM MiniJVM是一款使用python编写的简易JVM,能够从本地加载class文件并且执行绝大多数指令。 支持的功能 1.从本地磁盘加载class并解析 2.支持绝大多数指令集的执行 3.支持虚拟机内存分区以及对象的创建 4.支持方法的调用和参数传递 5.支持静态代码块的初始化 不支

keguoyu 60 Apr 1, 2022
SuperMario - Python programming class ending assignment SuperMario, using pygame

SuperMario - Python programming class ending assignment SuperMario, using pygame

mars 2 Jan 4, 2022
Class and mathematical functions for quaternion numbers.

Quaternions Class and mathematical functions for quaternion numbers. Installation Python This is a Python 3 module. If you don't have Python installed

null 3 Nov 8, 2022