Giter Club home page Giter Club logo

abcmeta's Introduction

abcmeta

GitHub Workflow Status PyPi version PyPI pyversions 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 ABC, abstractmethod


class Base(ABC):
    @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.

Support

If you find this project useful and want to support its development, consider buying me a coffee!

License

Please read the LICENSE file.

abcmeta's People

Contributors

kyleking avatar mortymacs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

abcmeta's Issues

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

abcmeta/abcmeta/__init__.py

Lines 157 to 187 in 4fef29b

# Make sure the derived class has implemented the abstract method.
if name not in cls.__dict__:
raise AttributeError(
"Derived class '{}' has not implemented '{}' method of the"
" parent class '{}'.".format(
cls.__name__, name, cls.__base__.__name__
)
)
derived_method = getattr(cls, name)
# Get methods signatures.
*obj_method_signature, obj_method_signature_str = _get_signature(obj)
*derived_method_signature, derived_method_signature_str = _get_signature(
derived_method
)
# Compare signatures.
diff = _compare_signatures(
obj_method_signature_str, derived_method_signature_str
)
# Raise signature error.
if diff:
diff_details = _compare_signatures_details(
obj_method_signature, derived_method_signature
)
raise AttributeError(
"Signature of the derived method is not the same as parent"
" class:\r\n{}".format(_prepare_text_to_raise(diff, diff_details))
)

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))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.