Welcome to runtime-final’s documentation!

runtime-final is a simple module that allows you declare final classes and methods that are validated at runtime.

This module is inspired by and is fully compatible with typing.final() decorator. See PEP-591 for more details about this topic. The compatiblity is described in documentation of final() decorator.

Installation

This module is hosted on PyPi and can easily be installed with:

$ python -m pip install runtime-final

Usage

For usage examples, See documentation of final() decorator.

Reference

Following are all the components that are provided by this module.

Metadata

runtime_final.__version__

The current version of the module.

runtime_final.__author__

The author of the package.

The copyright notice for this module.

@final decorator

runtime_final.final(target)

A decorator that declares a class or method as final.

A class declared as final with this decorator cannot be subclassed by other classes. Similarly, when methods of a class are declared as final, The subclasses cannot override them.

Trying to subclass final classes or overriding final methods will raise RuntimeError.

Here is an example of final classes:

@final
class User:
    pass

# The following line will raise RuntimeError
class SpecialUser(User):
    pass

And final methods:

class User:
    @final
    def delete(self):
        pass

class SpecialUser(User):
    # The following line will raise RuntimeError
    def delete(self):
        pass

Note

When using this decorator with special attributes such as staticmethod(), classmethod() and property(), This decorator should be placed above the relevant decorator for that special attribute.

E.g:

# Correct:
@final
@property
def foo(self):
    ...

# Wrong:
@property
@final
def foo(self):
    ...

This decorator is also fully compatible with the typing.final(). In applications where type checkers need to understand the usage of final decorator, the typing.TYPE_CHECKING constant can be used:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    # Type checkers will consider this clause but
    # this will not execute at runtime.
    from typing import final
else:
    # Type checkers will ignore this clause but
    # this is always executed at runtime.
    from runtime_final import final

Helpers

runtime_final.is_final(target)

Indicates whether a class or function is declared as final.

Parameters

target – The class or method to check for.

Return type

bool

runtime_final.get_final_methods(target)

Gets the final methods of given class.

Parameters

target (type) – The class to get final methods for.

Returns

The tuple of function objects that are marked as final.

Return type

tuple