All Projects → dry-python → classes

dry-python / classes

Licence: BSD-2-Clause License
Smart, pythonic, ad-hoc, typed polymorphism for Python

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to classes

Returns
Make your functions return something meaningful, typed, and safe!
Stars: ✭ 2,015 (+337.09%)
Mutual labels:  fp, mypy, mypy-stubs, mypy-plugins
safe-string-interpolation
A type driven approach to string interpolation, aiming at consistent, secure, and only-human-readable logs and console outputs !
Stars: ✭ 14 (-96.96%)
Mutual labels:  fp, typesafety
pybind11-stubgen
Generates stubs for python modules (targeted to C++ extensions compiled with pybind11)
Stars: ✭ 103 (-77.66%)
Mutual labels:  mypy, pep561
fpEs
Functional Programming for EcmaScript(Javascript)
Stars: ✭ 40 (-91.32%)
Mutual labels:  fp
vim-mypy
Vim plugin for executing Python's optional static type checker MyPy (http://mypy-lang.org/)
Stars: ✭ 89 (-80.69%)
Mutual labels:  mypy
BFSG
BFSG - BruteForce String Generator 😾
Stars: ✭ 16 (-96.53%)
Mutual labels:  mypy
alleycat-reactive
A simple Python library to provide an API to implement the Reactive Object Pattern (ROP).
Stars: ✭ 15 (-96.75%)
Mutual labels:  fp
php-finder refactoring-kata
🐘🔍Incomprehensible Finder Refactoring Kata port for PHP
Stars: ✭ 22 (-95.23%)
Mutual labels:  fp
pyroclastic
Functional dataflow through composable computations
Stars: ✭ 17 (-96.31%)
Mutual labels:  fp
concise-cheat-sheets
Cheat Sheets for programming languages and tools
Stars: ✭ 98 (-78.74%)
Mutual labels:  typeclasses
aiorwlock
Read/Write Lock - synchronization primitive for asyncio
Stars: ✭ 90 (-80.48%)
Mutual labels:  mypy
mmpm
MagicMirror Package Manager
Stars: ✭ 104 (-77.44%)
Mutual labels:  mypy
tradeio
A disciplined way to purely functional domain models in Scala
Stars: ✭ 19 (-95.88%)
Mutual labels:  fp
fs2-google-pubsub
Google Cloud Pub/Sub stream-based client built on top of cats-effect, fs2 and http4s.
Stars: ✭ 32 (-93.06%)
Mutual labels:  fp
hkts
Functional programming tools: option, either, task, state, optics, etc.
Stars: ✭ 20 (-95.66%)
Mutual labels:  fp
php-slang
The place where PHP meets Functional Programming
Stars: ✭ 107 (-76.79%)
Mutual labels:  fp
order-taking
Idris version of Domain Modeling Made Functional Book.
Stars: ✭ 113 (-75.49%)
Mutual labels:  fp
Swift-3-Functional-Programming
Code repository for Swift 3 Functional Programming, published by Packt
Stars: ✭ 78 (-83.08%)
Mutual labels:  fp
rubric
Linter Config Initializer for Python
Stars: ✭ 21 (-95.44%)
Mutual labels:  mypy
lzdash
Lazy / non-strict evaluation in JavaScript
Stars: ✭ 14 (-96.96%)
Mutual labels:  fp

classes

classes logo


Build Status codecov Documentation Status Python Version wemake-python-styleguide Telegram chat


Smart, pythonic, ad-hoc, typed polymorphism for Python.

Features

  • Provides a bunch of primitives to write declarative business logic
  • Enforces better architecture
  • Fully typed with annotations and checked with mypy, PEP561 compatible
  • Allows to write a lot of simple code without inheritance or interfaces
  • Pythonic and pleasant to write and to read (!)
  • Easy to start: has lots of docs, tests, and tutorials

Installation

pip install classes

You also need to configure mypy correctly and install our plugin:

# In setup.cfg or mypy.ini:
[mypy]
plugins =
  classes.contrib.mypy.classes_plugin

Without this step, your project will report type-violations here and there.

We also recommend to use the same mypy settings we use.

Make sure you know how to get started, check out our docs!

Example

Imagine, that you want to bound implementation to some particular type. Like, strings behave like this, numbers behave like that, and so on.

The good realworld example is djangorestframework. It is build around the idea that different data types should be converted differently to and from json format.

What is the "traditional" (or outdated if you will!) approach? To create tons of classes for different data types and use them.

That's how we end up with classes like so:

class IntField(Field):
    def from_json(self, value):
        return value

    def to_json(self, value):
        return value

It literally has a lot of problems:

  • It is hard to type this code. How can I be sure that my json is parseable by the given schema?
  • It produces a lot of boilerplate
  • It has complex API: there are usually several methods to override, some fields to adjust. Moreover, we use a class, not a simple function
  • It is hard to extend the default library for new custom types you will have in your own project
  • It is hard to override

There should be a better way of solving this problem! And typeclasses are a better way!

How would new API look like with this concept?

>>> from typing import Union
>>> from classes import typeclass

>>> @typeclass
... def to_json(instance) -> str:
...     """This is a typeclass definition to convert things to json."""

>>> @to_json.instance(int)
... @to_json.instance(float)
... def _to_json_int(instance: Union[int, float]) -> str:
...     return str(instance)

>>> @to_json.instance(bool)
... def _to_json_bool(instance: bool) -> str:
...     return 'true' if instance else 'false'

>>> @to_json.instance(list)
... def _to_json_list(instance: list) -> str:
...     return '[{0}]'.format(
...         ', '.join(to_json(list_item) for list_item in instance),
...     )

See how easy it is to works with types and implementation?

Typeclass is represented as a regular function, so you can use it like one:

>>> to_json(True)
'true'
>>> to_json(1)
'1'
>>> to_json([False, 1, 2.5])
'[false, 1, 2.5]'

And it easy to extend this typeclass with your own classes as well:

# Pretending to import the existing library from somewhere:
# from to_json import to_json

>>> import datetime as dt

>>> @to_json.instance(dt.datetime)
... def _to_json_datetime(instance: dt.datetime) -> str:
...     return instance.isoformat()

>>> to_json(dt.datetime(2019, 10, 31, 12, 28, 00))
'2019-10-31T12:28:00'

That's how simple, safe, and powerful typeclasses are! Make sure to check out our full docs to learn more.

More!

Want more? Go to the docs! Or read these articles:

⭐️

Drylabs maintains dry-python and helps those who want to use it inside their organizations.

Read more at drylabs.io

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].