8000 Adds first docs · dry-python/classes@dc415a4 · GitHub
[go: up one dir, main page]

Skip to content

Commit dc415a4

Browse files
committed
Adds first docs
1 parent c976b7d commit dc415a4

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed

docs/pages/concept.rst

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,53 @@ To use typeclasses you should understand these steps:
5858
F2 --> F2
5959
F2 --> F3["Calling"]
6060

61-
# TODO: cover each steps
62-
# TODO: json example for simple types
61+
Let's walk through this process step by step.
62+
The first on is "Typeclass definition", where we create a new typeclass:
63+
64+
.. code:: python
65+
66+
>>> from classes import typeclass
67+
>>> @typeclass
68+
... def json(instance) -> str:
69+
... """That's definition!"""
70+
...
71+
72+
When typeclass is defined it only has a name and a signature
73+
that all instances will share.
74+
Let's define some instances:
75+
76+
.. code:: python
77+
78+
>>> @json.instance(str)
79+
... def _json_str(instance: str) -> str:
80+
... return '"{0}"'.format(instance)
81+
...
82+
>>> @json.instance(int)
83+
... @json.instance(float)
84+
... def _json_int_float(instance) -> str:
85+
... return str(instance)
86+
...
87+
88+
That's how we define instances for our typeclass.
89+
These instances will be executed when the corresponding type will be supplied.
90+
91+
And the last step is to call our typeclass
92+
with different value of different types:
93+
94+
.. code:: python
95+
96+
>>> json('text')
97+
'"text"'
98+
>>> json(1)
99+
'1'
100+
>>> json(1.5)
101+
'1.5'
102+
103+
That's it. There's nothing extra about typeclasses. They can be:
104+
105+
- defined
106+
- extended by new instances
107+
- and called
63108

64109

65110
singledispatch
@@ -68,3 +113,6 @@ singledispatch
68113
One may ask, what is the difference
69114
with `singledispatch <https://docs.python.org/3/library/functools.html#functools.singledispatch>`_
70115
function from the standard library?
116+
117+
The thing about ``singledispatch`` is that it allows almost the same features.
118+
But, it lacks type-safety. For example,

docs/pages/typesafety.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.. _typesafety:
2+
13
Type-safety
24
===========
35

0 commit comments

Comments
 (0)
0