Blame view

doc/codestyle_examples/codestyle_first.py 20.5 KB
61165321   Etienne Pallier   nouveau my_packag...
1
2
#!/usr/bin/env python3

b999fd50   Etienne Pallier   Nouvelle version ...
3
4
"""
=================================================================
46b415a3   Etienne Pallier   update of python ...
5
6

    This MODULE is used as a reference for Python source code style & documentation
b999fd50   Etienne Pallier   Nouvelle version ...
7

16414ee4   Etienne Pallier   new doc/codestyle...
8
9
    VERSION 24.02.2022
    
b999fd50   Etienne Pallier   Nouvelle version ...
10
11
    This file conforms to the Sphinx Napoleon syntax :
    https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html
16414ee4   Etienne Pallier   new doc/codestyle...
12
13
14
15
16
    
    Ref :
    
    - Sphinx generalities on RST format : https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html
    - Sphinx autodoc : https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html
9d8c5b5c   Etienne Pallier   Toute premiere ve...
17
18
    - Sphinx autodocsumm : https://autodocsumm.readthedocs.io/en/latest/index.html
    - Sphinx autosummary : https://www.sphinx-doc.org/en/master/usage/extensions/autosummary.html
16414ee4   Etienne Pallier   new doc/codestyle...
19
20
21
22
23
24
25
    - Sphinx apidoc (1) for autogeneration of files in the source folder : https://www.sphinx-doc.org/en/master/man/sphinx-apidoc.html
    - Sphinx apidoc (2) more explanations : https://samnicholls.net/2016/06/15/how-to-sphinx-readthedocs
    - Sphinx inheritance diagrams : https://www.sphinx-doc.org/en/master/usage/extensions/inheritance.html
    - Typehints cheatsheet : https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
    - Doctests : https://docs.python.org/fr/3/library/doctest.html
    - Mixins : https://www.thedigitalcatonline.com/blog/2020/03/27/mixin-classes-in-python
    - Data Classes (3.7+) : https://realpython.com/python-data-classes
1b109b72   Etienne Pallier   New version of th...
26
27
28
29

    Changes :

    - added new type annotation : Literal
1b109b72   Etienne Pallier   New version of th...
30
    - added new types : NamedTuple, Dataclass, Enum, TypedDict
1b109b72   Etienne Pallier   New version of th...
31
    - added custom and derived Exceptions
46b415a3   Etienne Pallier   update of python ...
32

b999fd50   Etienne Pallier   Nouvelle version ...
33
34
=================================================================
"""
c5fb1b6a   Etienne Pallier   new my_package1.m...
35

b999fd50   Etienne Pallier   Nouvelle version ...
36
# This import MUST BE at the very beginning of the file (or syntax error...)
61165321   Etienne Pallier   nouveau my_packag...
37
from __future__ import annotations
16414ee4   Etienne Pallier   new doc/codestyle...
38
from dataclasses import dataclass, field
61165321   Etienne Pallier   nouveau my_packag...
39

b999fd50   Etienne Pallier   Nouvelle version ...
40

61165321   Etienne Pallier   nouveau my_packag...
41
# TODO :
61165321   Etienne Pallier   nouveau my_packag...
42
43
# - exception (custom)
# - dataclass
b999fd50   Etienne Pallier   Nouvelle version ...
44
45
# - NamedTuple
# - Enum
61165321   Etienne Pallier   nouveau my_packag...
46
47


97a4003f   Etienne Pallier   nouveau my_packag...
48
49
50
51
52
# '''
# =================================================================
#     PACKAGES IMPORT
# =================================================================
# '''
61165321   Etienne Pallier   nouveau my_packag...
53

b999fd50   Etienne Pallier   Nouvelle version ...
54
# --- 1) GENERAL PURPOSE IMPORTS ---
61165321   Etienne Pallier   nouveau my_packag...
55

1b109b72   Etienne Pallier   New version of th...
56
57
58
from typing import Dict, List, Tuple, Sequence, Any, TypeVar, Union, Callable, Literal
import typing

61165321   Etienne Pallier   nouveau my_packag...
59
60
import platform
from datetime import date
c5fb1b6a   Etienne Pallier   new my_package1.m...
61
import random
61165321   Etienne Pallier   nouveau my_packag...
62

b999fd50   Etienne Pallier   Nouvelle version ...
63
# --- 2) PROJECT SPECIFIC IMPORTS ---
61165321   Etienne Pallier   nouveau my_packag...
64

b999fd50   Etienne Pallier   Nouvelle version ...
65
66
67
68
# from django.conf import settings as djangosettings
# from common.models import AgentSurvey, AgentCmd, AgentLogs
# from src.core.pyros_django.obsconfig.configpyros import ConfigPyros
# from device_controller.abstract_component.device_controller import (
97a4003f   Etienne Pallier   nouveau my_packag...
69
#    DCCNotFoundException, UnknownGenericCmdException, UnimplementedGenericCmdException, UnknownNativeCmdException
b999fd50   Etienne Pallier   Nouvelle version ...
70
# )
61165321   Etienne Pallier   nouveau my_packag...
71

61165321   Etienne Pallier   nouveau my_packag...
72

97a4003f   Etienne Pallier   nouveau my_packag...
73
74
75
76
77
# '''
# =================================================================
#     GENERAL MODULE CONSTANTS & FUNCTIONS DEFINITIONS
# =================================================================
# '''
61165321   Etienne Pallier   nouveau my_packag...
78

b999fd50   Etienne Pallier   Nouvelle version ...
79
80
81
#
# - (General) Module level Constants
#
61165321   Etienne Pallier   nouveau my_packag...
82

61165321   Etienne Pallier   nouveau my_packag...
83
84
85

IS_WINDOWS = platform.system() == "Windows"

e756352f   Etienne Pallier   updated Agent : t...
86
87
DEBUG = False

61165321   Etienne Pallier   nouveau my_packag...
88

61165321   Etienne Pallier   nouveau my_packag...
89

b999fd50   Etienne Pallier   Nouvelle version ...
90
# - Typehint : Union (but not yet '|', only available with python 3.10)
c5fb1b6a   Etienne Pallier   new my_package1.m...
91

b999fd50   Etienne Pallier   Nouvelle version ...
92
def general_function_that_returns_a_float(
1b109b72   Etienne Pallier   New version of th...
93
    arg_a: int, arg_b: str | int, arg_c: float = 1.2, arg_d: bool = True
b999fd50   Etienne Pallier   Nouvelle version ...
94
) -> float:
1b109b72   Etienne Pallier   New version of th...
95
    """This function illustrates Typehint 'Union' (or '|')
61165321   Etienne Pallier   nouveau my_packag...
96
97
98

    Args:
        arg_a: the path of the file to wrap
1b109b72   Etienne Pallier   New version of th...
99
        arg_b: instance to wrap
61165321   Etienne Pallier   nouveau my_packag...
100
101
102
103
104
105
106
107
108
109
        arg_c: toto
        arg_d: whether or not to delete the file when the File instance is destructed

    Returns:
        A buffered writable file descriptor

    Raises:
        AttributeError: The ``Raises`` section is a list of all exceptions
            that are relevant to the interface.
        ValueError: If `arg_a` is equal to `arg_b`.
1b109b72   Etienne Pallier   New version of th...
110
111
112
113
114
115

    Usage:

        general_function_that_returns_a_float(arg_a=1, arg_b="toto")    # => OK

        general_function_that_returns_a_float(arg_a=1, arg_b=1.2)       # => KO (float not allowed)
b999fd50   Etienne Pallier   Nouvelle version ...
116
    """
61165321   Etienne Pallier   nouveau my_packag...
117
118
119
120
121
122
123
124
125

    # comment on a
    a = 1

    # comment on b
    b = 2

    return 3.5

61165321   Etienne Pallier   nouveau my_packag...
126

b999fd50   Etienne Pallier   Nouvelle version ...
127
128
129
130
131
132
# - Typehint : Tuple (immutable)

def general_function_that_returns_a_tuple_of_3_elem(
    a: int, b: int = 2, c: str = "titi"
) -> Tuple[int, float, str]:
    """This function illustrates Typehint 'Tuple' (immutable)
61165321   Etienne Pallier   nouveau my_packag...
133
134
135
136
137

    Args:
        a: the path of the file to wrap
        b: instance to wrap
        c: toto
61165321   Etienne Pallier   nouveau my_packag...
138

b999fd50   Etienne Pallier   Nouvelle version ...
139
140
141
142
143
    Usage:

    >>> e = general_function_that_returns_a_tuple_of_3_elem(1, 2, 'toto')
    >>> e
    (1, 2, 'toto toto')
61165321   Etienne Pallier   nouveau my_packag...
144

b999fd50   Etienne Pallier   Nouvelle version ...
145
    You can name parameters if you don't pass all of them (here we don't pass optional parameter 'b') :
61165321   Etienne Pallier   nouveau my_packag...
146

b999fd50   Etienne Pallier   Nouvelle version ...
147
148
149
150
151
152
153
154
155
156
157
158
159
    >>> e = general_function_that_returns_a_tuple_of_3_elem(c='toto', a=1)
    >>> e
    (1, 2, 'toto toto')

    >>> f,g,h = general_function_that_returns_a_tuple_of_3_elem(c='toto', a=1, b=2)
    >>> f,g,h
    (1, 2, 'toto toto')

    """
    return (a, b, c + " toto")


# - Typehint : Sequence = List (mutable) or Tuple (immutable)
61165321   Etienne Pallier   nouveau my_packag...
160

c5fb1b6a   Etienne Pallier   new my_package1.m...
161
def square(elems: Sequence[float]) -> List[float]:
b999fd50   Etienne Pallier   Nouvelle version ...
162
163
164
    """This function illustrates Typehint 'Sequence'

    Takes a Sequence (either List of Tuple) as input, and send a List as output
61165321   Etienne Pallier   nouveau my_packag...
165

c5fb1b6a   Etienne Pallier   new my_package1.m...
166
167
168
169
    Usage:

    >>> square( [1,2,3] )
    [1, 4, 9]
b999fd50   Etienne Pallier   Nouvelle version ...
170

c5fb1b6a   Etienne Pallier   new my_package1.m...
171
172
    >>> square( (1,2,3) )
    [1, 4, 9]
b999fd50   Etienne Pallier   Nouvelle version ...
173
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
174

b999fd50   Etienne Pallier   Nouvelle version ...
175
    return [x ** 2 for x in elems]
c5fb1b6a   Etienne Pallier   new my_package1.m...
176
177


b999fd50   Etienne Pallier   Nouvelle version ...
178
# - Typehint : TypeAlias
c5fb1b6a   Etienne Pallier   new my_package1.m...
179

c5fb1b6a   Etienne Pallier   new my_package1.m...
180
181
182
Card = Tuple[str, str]
Deck = List[Card]

b999fd50   Etienne Pallier   Nouvelle version ...
183
184
185
SUITS = "♠ ♡ ♢ ♣".split()
RANKS = "2 3 4 5 6 7 8 9 10 J Q K A".split()

c5fb1b6a   Etienne Pallier   new my_package1.m...
186
187

def create_deck_without_alias(shuffle: bool = False) -> List[Tuple[str, str]]:
b999fd50   Etienne Pallier   Nouvelle version ...
188
189
190
191
    """This function (and the next one) illustrates Typehint 'TypeAlias'

    Create a new deck of 52 cards
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
192
193
194
195
196
197
198
    deck = [(s, r) for r in RANKS for s in SUITS]
    if shuffle:
        random.shuffle(deck)
    return deck


def create_deck_with_alias(shuffle: bool = False) -> Deck:
b999fd50   Etienne Pallier   Nouvelle version ...
199
    """This function (and the previous one) illustrates Typehint 'TypeAlias'
16414ee4   Etienne Pallier   new doc/codestyle...
200

b999fd50   Etienne Pallier   Nouvelle version ...
201
    Create a new deck of 52 cards
c5fb1b6a   Etienne Pallier   new my_package1.m...
202
203
204
205
206
207
208
209
210
211
212
213
214

    Card = Tuple[str, str]

    Deck = List[Card]

    Return Deck
    """
    deck = [(s, r) for r in RANKS for s in SUITS]
    if shuffle:
        random.shuffle(deck)
    return deck


b999fd50   Etienne Pallier   Nouvelle version ...
215
# - Typehint : Generics avec Sequence, Any, TypeVar
c5fb1b6a   Etienne Pallier   new my_package1.m...
216
217

def choose_from_list_of_Any_returns_a_Any(items: Sequence[Any]) -> Any:
b999fd50   Etienne Pallier   Nouvelle version ...
218
219
220
221
    """This function illustrates Typehint 'Generics'

    Option1 (BAD) : avoid using 'Any' because too general
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
222
223
224
    return random.choice(items)


b999fd50   Etienne Pallier   Nouvelle version ...
225
226
227
T = TypeVar("T")


c5fb1b6a   Etienne Pallier   new my_package1.m...
228
def choose_from_list_of_a_specific_type_returns_same_type(items: Sequence[T]) -> T:
b999fd50   Etienne Pallier   Nouvelle version ...
229
230
231
    """This function illustrates Typehint 'Generics'

    Option2 (BETTER) : prefer 'TypeVar' instead of 'Any'
c5fb1b6a   Etienne Pallier   new my_package1.m...
232
233

    T = TypeVar("T")
b999fd50   Etienne Pallier   Nouvelle version ...
234
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
235
236
237
    return random.choice(items)


b999fd50   Etienne Pallier   Nouvelle version ...
238
T_str_flt = TypeVar("T_str_flt", str, float)
c5fb1b6a   Etienne Pallier   new my_package1.m...
239

c5fb1b6a   Etienne Pallier   new my_package1.m...
240

b999fd50   Etienne Pallier   Nouvelle version ...
241
242
243
244
245
246
247
248
249
250
def choose_from_list_of_a_specific_constrained_type_returns_same_type(
    items: Sequence[T_str_flt],
) -> T_str_flt:
    """This function illustrates Typehint 'Generics'

    Option3 (still BETTER) : use a 'constrained TypeVar'

    T_str_flt = TypeVar("T_str_flt", str, float)

    (you could name 'T_str_flt' as you want, for example, 'Choosable'...)
c5fb1b6a   Etienne Pallier   new my_package1.m...
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266

    => the function accepts only sequence of str or float:

    - if str: return str

    - if float: return float

    Usage:

    choose(["Guido", "Jukka", "Ivan"])    => str, OK

    choose([1, 2, 3])                => float, OK (car int subtype of float)

    choose([True, 42, 3.14])        => float, OK (car bool subtype of int which is subtype of float)

    choose(["Python", 3, 7])            => object, KO (rejected)
16414ee4   Etienne Pallier   new doc/codestyle...
267

b999fd50   Etienne Pallier   Nouvelle version ...
268
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
269
270
271
272

    return random.choice(items)


b999fd50   Etienne Pallier   Nouvelle version ...
273
# - Typehint : Callable
c5fb1b6a   Etienne Pallier   new my_package1.m...
274
275

def create_greeting(congrat: str, name: str, nb: int) -> str:
c5fb1b6a   Etienne Pallier   new my_package1.m...
276
277
278
    return f"{congrat} {name} {nb}"


b999fd50   Etienne Pallier   Nouvelle version ...
279
280
281
282
283
def do_twice(
    func: Callable[[str, str, int], str], arg1: str, arg2: str, arg3: int
) -> None:
    """This function illustrates Typehint 'Callable'

c5fb1b6a   Etienne Pallier   new my_package1.m...
284
285
286
287
288
    Usage:

    >>> do_twice(create_greeting, "Hello", "Jekyll", 1)
    Hello Jekyll 1
    Hello Jekyll 1
b999fd50   Etienne Pallier   Nouvelle version ...
289
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
290
291
292
293
    print(func(arg1, arg2, arg3))
    print(func(arg1, arg2, arg3))


1b109b72   Etienne Pallier   New version of th...
294
295
# - Typehint : typing.Literal (new in 3.8)

16414ee4   Etienne Pallier   new doc/codestyle...
296
def validate_simple(data: Any) -> Literal[True]:
1b109b72   Etienne Pallier   New version of th...
297
    """This function illustrates Typehint 'Literal' (new in 3.8)
16414ee4   Etienne Pallier   new doc/codestyle...
298

1b109b72   Etienne Pallier   New version of th...
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    => should always return True
    """
    pass


MODE = Literal['r', 'rb', 'w', 'wb']


def open_helper(file: str, mode: MODE) -> str:
    """This function illustrates Typehint 'Literal' (new in 3.8)

    (Type alias :)

    MODE = Literal['r', 'rb', 'w', 'wb']

    Usage:
16414ee4   Etienne Pallier   new doc/codestyle...
315

1b109b72   Etienne Pallier   New version of th...
316
317
318
319
320
    OK :

    >>> open_helper('/some/path', 'r')

    Error :
16414ee4   Etienne Pallier   new doc/codestyle...
321

1b109b72   Etienne Pallier   New version of th...
322
323
324
325
326
327
    >>> open_helper('/other/path', 'typo')  
    """

    pass


c5fb1b6a   Etienne Pallier   new my_package1.m...
328
329
# '''
#    *******************************
b999fd50   Etienne Pallier   Nouvelle version ...
330
#      CUSTOM EXCEPTIONS CLASSES
c5fb1b6a   Etienne Pallier   new my_package1.m...
331
332
333
334
335
336
#    *******************************
#    See https://docs.python.org/3/tutorial/errors.html
# '''


class DCCNotFoundException(Exception):
b999fd50   Etienne Pallier   Nouvelle version ...
337
338
    """Raised when a specific DCC is not available"""

61165321   Etienne Pallier   nouveau my_packag...
339
340
341
    pass


c5fb1b6a   Etienne Pallier   new my_package1.m...
342
class UnknownGenericCmdArgException(Exception):
b999fd50   Etienne Pallier   Nouvelle version ...
343
    """Raised when a GENERIC cmd argument is not recognized by the controller (no native cmd available for the generic cmd)"""
c5fb1b6a   Etienne Pallier   new my_package1.m...
344
345
346
347
348
349
350
351
352
353

    def __init__(self, name: str, arg: str):
        self.name = name
        self.arg = arg

    def __str__(self):
        return f"The argument '{self.arg}' does not exist for generic cmd {self.name}"


class UnknownNativeCmdException(Exception):
b999fd50   Etienne Pallier   Nouvelle version ...
354
355
    """Raised when a NATIVE command name is not recognized by the controller"""

c5fb1b6a   Etienne Pallier   new my_package1.m...
356
357
358
359
360
    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs)


class UnimplementedGenericCmdException(Exception):
b999fd50   Etienne Pallier   Nouvelle version ...
361
362
    """Raised when a GENERIC cmd has no implementation in the controller (no native cmd available for the generic cmd)"""

c5fb1b6a   Etienne Pallier   new my_package1.m...
363
364
365
366
    def __str__(self):
        return f"({type(self).__name__}): Device Generic command has no implementation in the controller"


1b109b72   Etienne Pallier   New version of th...
367
368
class MyImprovedException(Exception):
    """Improved Exeption class with predefined list of standard error messages, and optional specific message
16414ee4   Etienne Pallier   new doc/codestyle...
369

1b109b72   Etienne Pallier   New version of th...
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
    Usage:

    >>> e = MyImprovedException(MyImprovedException.ERROR_BAD_PARAM)
    >>> e.error_msg
    'Bad Parameter'
    >>> e
    MyImprovedException('Bad Parameter')
    >>> print(e)
    (MyImprovedException): Bad Parameter

    >>> e = MyImprovedException(MyImprovedException.ERROR_BAD_PARAM, "my specific message added")
    >>> e
    MyImprovedException('Bad Parameter', 'my specific message added')
    >>> print(e)
    (MyImprovedException): Bad Parameter ; Specific message: my specific message added
    """

    # List of standard error messages
    ERROR_UNDEFINED_PARAM = "Parameter not defined"
    ERROR_BAD_PARAM = "Bad Parameter"
    ERROR_MISSING_PARAM = "a Parameter is missing"
    ERROR_TOO_MANY_PARAM = "Too many Parameters"

    def __init__(self, error_msg: str, specific_msg: str = None):
16414ee4   Etienne Pallier   new doc/codestyle...
394
        # super().__init__(error_msg)
1b109b72   Etienne Pallier   New version of th...
395
396
397
398
399
400
401
402
403
404
405
406
407
408
        self.error_msg = error_msg
        self.specific_msg = specific_msg

    def __str__(self):
        #msg = f"({type(self).__name__}): {self.error_msg}"
        msg = f"({self.__class__.__name__}): {self.error_msg}"
        if self.specific_msg:
            msg += f" ; Specific message: {self.specific_msg}"
        return msg


class MyOwnDerivedException(MyImprovedException):
    """
    Usage:
16414ee4   Etienne Pallier   new doc/codestyle...
409

1b109b72   Etienne Pallier   New version of th...
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
    >>> try:
    ...     print("doing something dangerous...")
    ...     raise MyOwnDerivedException(MyOwnDerivedException.ERROR_MISSING_PARAM)
    ... except MyOwnDerivedException as e:
    ...     print(e)
    doing something dangerous...
    (MyOwnDerivedException): a Parameter is missing

    >>> try:
    ...     print("doing something dangerous...")
    ...     raise MyOwnDerivedException(MyOwnDerivedException.ERROR_NEW_CASE2, 'my own special message')
    ... except MyImprovedException as e:  # we can use superclass also
    ...     print(e)
    doing something dangerous...
    (MyOwnDerivedException): Nouveau cas d'erreur 2 ; Specific message: my own special message

    General example :

    >>> try:
    ...     # do something
    ...     pass
    ...
    ... except ValueError:
    ...     # handle ValueError exception
    ...     pass
    ...
    ... except (TypeError, ZeroDivisionError):
    ...     # handle multiple exceptions
    ...     # TypeError and ZeroDivisionError
    ...     pass
    ...
    ... except:
    ...     # handle all other exceptions
    ...     pass

    """
    # Add new specific error cases for this exception type:
    ERROR_NEW_CASE1 = "Nouveau cas d'erreur 1"
    ERROR_NEW_CASE2 = "Nouveau cas d'erreur 2"

16414ee4   Etienne Pallier   new doc/codestyle...
450

1b109b72   Etienne Pallier   New version of th...
451
452
453
454
455
456
457
458
459
'''
try:
    print("doing something dangerous...")
    raise MyOwnDerivedException(MyOwnDerivedException.ERROR_MISSING_PARAM)
except MyOwnDerivedException as e:
    print(e)
'''


61165321   Etienne Pallier   nouveau my_packag...
460
461
# '''
# =================================================================
b999fd50   Etienne Pallier   Nouvelle version ...
462
#     GENERAL CLASSES
61165321   Etienne Pallier   nouveau my_packag...
463
464
# =================================================================
# '''
c5fb1b6a   Etienne Pallier   new my_package1.m...
465
466
467
468
469
470
471
472
473
474


class MySuperClass1:
    pass


class MySuperClass2:
    pass


b999fd50   Etienne Pallier   Nouvelle version ...
475
476
477
478
479
# '''
# =================================================================
#     - CLASS MySimpleClass
# =================================================================
# '''
c5fb1b6a   Etienne Pallier   new my_package1.m...
480

61165321   Etienne Pallier   nouveau my_packag...
481
class MySimpleClass(MySuperClass1, MySuperClass2):
b999fd50   Etienne Pallier   Nouvelle version ...
482
    """a Class with multi-inheritance
61165321   Etienne Pallier   nouveau my_packag...
483
484
485
486

    blabla

    blabla
b999fd50   Etienne Pallier   Nouvelle version ...
487
    """
61165321   Etienne Pallier   nouveau my_packag...
488
489

    #
c5fb1b6a   Etienne Pallier   new my_package1.m...
490
    # Class attributes
61165321   Etienne Pallier   nouveau my_packag...
491
492
493
    #

    names: List[str] = ["Guido", "Jukka", "Ivan"]
b999fd50   Etienne Pallier   Nouvelle version ...
494
    """ List is mutable"""
61165321   Etienne Pallier   nouveau my_packag...
495
496

    version: Tuple[int, int, int] = (3, 7, 1)
b999fd50   Etienne Pallier   Nouvelle version ...
497
    """ Tuple is IMMutable"""
61165321   Etienne Pallier   nouveau my_packag...
498
499

    options: Dict[str, bool] = {"centered": False, "capitalize": True}
b999fd50   Etienne Pallier   Nouvelle version ...
500
    """ Dict (is mutable) """
61165321   Etienne Pallier   nouveau my_packag...
501
502
503

    my_attr1: dict = {}
    current_file = None
61165321   Etienne Pallier   nouveau my_packag...
504
505

    #
c5fb1b6a   Etienne Pallier   new my_package1.m...
506
    # Class methods
61165321   Etienne Pallier   nouveau my_packag...
507
508
509
    #

    def __init__(self, a: int, b: float) -> None:
b999fd50   Etienne Pallier   Nouvelle version ...
510
        """
61165321   Etienne Pallier   nouveau my_packag...
511
512
513
514
        La methode __init__ doit toujours retourner "None"

        Args:
            a: blabla
b999fd50   Etienne Pallier   Nouvelle version ...
515
        """
61165321   Etienne Pallier   nouveau my_packag...
516
517
518
        c = 1
        d = 2

61165321   Etienne Pallier   nouveau my_packag...
519
    def __str__(self) -> str:
b999fd50   Etienne Pallier   Nouvelle version ...
520
        """
61165321   Etienne Pallier   nouveau my_packag...
521
        La methode __str__ doit toujours retourner "str"
b999fd50   Etienne Pallier   Nouvelle version ...
522
        """
61165321   Etienne Pallier   nouveau my_packag...
523
524
525
        return "toto"

    def my_method2(self, a: int, b: float) -> None:
b999fd50   Etienne Pallier   Nouvelle version ...
526
        """Method that returns nothing"""
61165321   Etienne Pallier   nouveau my_packag...
527
528
529
530
531
532
        a = 1
        b = 2


# '''
# =================================================================
b999fd50   Etienne Pallier   Nouvelle version ...
533
#     - CLASS Person
61165321   Etienne Pallier   nouveau my_packag...
534
535
536
537
# =================================================================
# '''

class Person:
b999fd50   Etienne Pallier   Nouvelle version ...
538
    """Class to create a person, in several ways (several Factory methods)
61165321   Etienne Pallier   nouveau my_packag...
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572

    => Illustrate difference btw static and class methods

    Usage:

    1) Classic Constructor :

    >>> person1 = Person('Alfredo', 21)

    2) Class method (Factory) :

    >>> person2 = Person.fromBirthYear('Peter', 2000)
    >>> person2.age
    22

    3) Another class method (Factory) :

    >>> person3 = Person.twin('John', person2)
    >>> person3.age == person2.age
    True
    >>> person3.name == person2.name
    False

    4) Static method (does not need access to the class attributes or methods) :

    >>> Person.isAdult(22)
    True

    """

    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

61165321   Etienne Pallier   nouveau my_packag...
573
574
    @classmethod
    def fromBirthYear(cls, name: str, year: int) -> Person:
b999fd50   Etienne Pallier   Nouvelle version ...
575
        """A class method to create a Person object by birth year
16414ee4   Etienne Pallier   new doc/codestyle...
576

c5fb1b6a   Etienne Pallier   new my_package1.m...
577
        NB : return type 'Person' is possible because of: 'from __future__ import annotations'
b999fd50   Etienne Pallier   Nouvelle version ...
578
        """
61165321   Etienne Pallier   nouveau my_packag...
579
580
        return cls(name, date.today().year - year)

61165321   Etienne Pallier   nouveau my_packag...
581
582
    @classmethod
    def twin(cls, name: str, p: Person) -> Person:
b999fd50   Etienne Pallier   Nouvelle version ...
583
        """A class method to create a Person object from another"""
61165321   Etienne Pallier   nouveau my_packag...
584
585
        return cls(name, p.age)

61165321   Etienne Pallier   nouveau my_packag...
586
587
    @staticmethod
    def isAdult(age: int):
b999fd50   Etienne Pallier   Nouvelle version ...
588
        """A static method to check if a Person is adult or not"""
61165321   Etienne Pallier   nouveau my_packag...
589
590
591
592
593
        return age > 18


# '''
# =================================================================
1b109b72   Etienne Pallier   New version of th...
594
595
596
597
598
599
600
601
602
603
604
605
606
607
#     - CLASS Employee
# =================================================================
# '''

# class typing.NamedTuple : Typed version of collections.namedtuple()

class Employee(typing.NamedTuple):
    """Illustrates usage of collections.namedtuple & typing.NamedTuple

    See https://towardsdatascience.com/what-are-named-tuples-in-python-59dc7bd15680

    See https://www.netjstech.com/2020/01/named-tuple-python.html

    Usage:
16414ee4   Etienne Pallier   new doc/codestyle...
608

1b109b72   Etienne Pallier   New version of th...
609
    1) Here we use typing.NamedTuple :
16414ee4   Etienne Pallier   new doc/codestyle...
610

1b109b72   Etienne Pallier   New version of th...
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
    >>> andrew = Employee('Andrew', 'Brown', ['Develoer', 'Manager'], 'US')
    >>> print(andrew)
    Employee(first_name='Andrew', last_name='Brown', jobs=['Develoer', 'Manager'], country='US')

    >>> alice = Employee(first_name='Alice', last_name='Stevenson', jobs=['Product Owner'])
    >>> print(alice)
    Employee(first_name='Alice', last_name='Stevenson', jobs=['Product Owner'], country='France')
    >>> alice.last_name
    'Stevenson'
    >>> alice[1]
    'Stevenson'
    >>> for attr in alice: print(attr)
    Alice
    Stevenson
    ['Product Owner']
    France


    2) Here we define the same Employee as above, but using collections.namedtuple :
16414ee4   Etienne Pallier   new doc/codestyle...
630

1b109b72   Etienne Pallier   New version of th...
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
    >>> from collections import namedtuple
    >>> Employee = namedtuple('Employee', 'first_name last_name jobs country')

    or :

    >>> Employee = namedtuple('Employee', ['first_name', 'last_name', 'jobs', 'country'])

    """

    first_name: str
    last_name: str
    jobs: list
    country: str = "France"


# '''
# =================================================================
#     - CLASS Point2D
# =================================================================
# '''

# typing.TypedDict : Special construct to add type hints to a dictionary. At runtime it is a plain dict

class Point2D(typing.TypedDict):
    """Class to illustrate typing.TypedDict

    (Special construct to add type hints to a dictionary. At runtime it is a plain dict)

    See: https://adamj.eu/tech/2021/05/10/python-type-hints-how-to-use-typeddict/

16414ee4   Etienne Pallier   new doc/codestyle...
661

1b109b72   Etienne Pallier   New version of th...
662
    Usage:
16414ee4   Etienne Pallier   new doc/codestyle...
663

1b109b72   Etienne Pallier   New version of th...
664
665
666
    a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK

    b: Point2D = {'x': 1, 'y': 2}                   # KO (missing label)
16414ee4   Etienne Pallier   new doc/codestyle...
667

1b109b72   Etienne Pallier   New version of th...
668
    c: Point2D = {'z': 3, 'label': 'bad'}           # KO (z not defined)
16414ee4   Etienne Pallier   new doc/codestyle...
669

1b109b72   Etienne Pallier   New version of th...
670
671
    d: Point2D = {}                                 # KO (missing x, y, label)

16414ee4   Etienne Pallier   new doc/codestyle...
672

1b109b72   Etienne Pallier   New version of th...
673
    Definition (other possibilities):
16414ee4   Etienne Pallier   new doc/codestyle...
674

1b109b72   Etienne Pallier   New version of th...
675
    Point2D = TypedDict('Point2D', x=int, y=int, label=str)
16414ee4   Etienne Pallier   new doc/codestyle...
676

1b109b72   Etienne Pallier   New version of th...
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
    Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
    """
    x: int
    y: int
    label: str


def get_point() -> Point2D:
    return {
        'x': 1,
        'y': 2,
        'label': 'good'
    }


1b109b72   Etienne Pallier   New version of th...
692
693
694
695
696
697
698
699
# '''
# =================================================================
#     - CLASS Position
# =================================================================
# '''

# @dataclass : shortcut for class definition

1b109b72   Etienne Pallier   New version of th...
700
701
702
703
704
705

@dataclass
class Position:
    """@dataclass

    Class to illustrate Data Classes (@dataclass)
16414ee4   Etienne Pallier   new doc/codestyle...
706

1b109b72   Etienne Pallier   New version of th...
707
    See: https://realpython.com/python-data-classes
16414ee4   Etienne Pallier   new doc/codestyle...
708

1b109b72   Etienne Pallier   New version of th...
709
710
711
712
713
    A DataClass is a shortcut to define a "data structure" without method

    It is much like a NamedTuple, but "mutable", and with more features.

    Defines automatically a lot of things for you : 
16414ee4   Etienne Pallier   new doc/codestyle...
714

1b109b72   Etienne Pallier   New version of th...
715
    - __init__() (with self.x = x, self.y = y, ...)
16414ee4   Etienne Pallier   new doc/codestyle...
716

1b109b72   Etienne Pallier   New version of th...
717
    - __repr()__
16414ee4   Etienne Pallier   new doc/codestyle...
718

1b109b72   Etienne Pallier   New version of th...
719
720
721
    - __eq()__

    - order, sort, immutable or not (frozen=True), ...
16414ee4   Etienne Pallier   new doc/codestyle...
722

1b109b72   Etienne Pallier   New version of th...
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
    NB: on peut quand même ajouter des méthodes à une dataclass car c’est une classe normale...


    Definition alternatives :

    >>> from dataclasses import make_dataclass
    >>> Position = make_dataclass('Position', ['name', 'lat', 'lon'])

    Usage:

    >>> pos = Position('Oslo', 10.8, 59.9)
    >>> pos
    Position(name='Oslo', lat=10.8, lon=59.9)
    >>> pos.lon
    59.9
    """
16414ee4   Etienne Pallier   new doc/codestyle...
739

1b109b72   Etienne Pallier   New version of th...
740
741
    name: str
    lon: float
16414ee4   Etienne Pallier   new doc/codestyle...
742
    lat: float = 0.0  # with default value
1b109b72   Etienne Pallier   New version of th...
743
744
745
746
747


@dataclass
class PlayingCard:
    """@dataclass
16414ee4   Etienne Pallier   new doc/codestyle...
748

1b109b72   Etienne Pallier   New version of th...
749
750
751
752
753
754
755
756
757
    Class to illustrate Data Classes (@dataclass)
    """
    rank: str
    suit: str


@dataclass
class Deck:
    """@dataclass
16414ee4   Etienne Pallier   new doc/codestyle...
758

1b109b72   Etienne Pallier   New version of th...
759
760
761
762
763
    Class to illustrate Data Classes (@dataclass)

    Usage:

    >>> queen_of_hearts = PlayingCard('Q', 'Hearts')
16414ee4   Etienne Pallier   new doc/codestyle...
764

1b109b72   Etienne Pallier   New version of th...
765
    >>> ace_of_spades = PlayingCard('A', 'Spades')
16414ee4   Etienne Pallier   new doc/codestyle...
766

1b109b72   Etienne Pallier   New version of th...
767
768
769
770
771
772
773
774
    >>> two_cards = Deck([queen_of_hearts, ace_of_spades])
    """
    cards: List[PlayingCard]


@dataclass
class Cmd:
    """@dataclass
16414ee4   Etienne Pallier   new doc/codestyle...
775

1b109b72   Etienne Pallier   New version of th...
776
777
778
779
780
781
782
783
784
785
786
787
788
    PyROS example class to illustrate Data Classes 
    (@dataclass, and using 'field')

    Usage:

    >>> c = Cmd('get_timezone')

    >>> c = Cmd('do_init','do_init'),
    """

    generic_name: str = 'generic name'
    native_name: str = ''
    desc: str = 'Description'
16414ee4   Etienne Pallier   new doc/codestyle...
789
790
    # equivalent to "= {}" which is not allowed
    params: Dict[str, str] = field(default_factory=dict)
1b109b72   Etienne Pallier   New version of th...
791
792
793
794
795
796
797
798
    final_simul_response: str = 'simulator response'
    final_device_responses: Dict[str, str] = field(default_factory=dict)
    immediate_responses: Dict[str, str] = field(default_factory=dict)
    errors: Dict[str, str] = field(default_factory=dict)


# '''
# =================================================================
61165321   Etienne Pallier   nouveau my_packag...
799
800
801
802
#    Main function (definition)
# =================================================================
# '''

61165321   Etienne Pallier   nouveau my_packag...
803
def main() -> None:
b999fd50   Etienne Pallier   Nouvelle version ...
804
    """Comment on Main function definition"""
61165321   Etienne Pallier   nouveau my_packag...
805
806
    a = 1
    b = 2
b999fd50   Etienne Pallier   Nouvelle version ...
807
    c = a + b
61165321   Etienne Pallier   nouveau my_packag...
808

b999fd50   Etienne Pallier   Nouvelle version ...
809
810
    e = general_function_that_returns_a_tuple_of_3_elem(c="toto", a=1, b=2)
    # print(e)
61165321   Etienne Pallier   nouveau my_packag...
811
812

    import doctest
b999fd50   Etienne Pallier   Nouvelle version ...
813

61165321   Etienne Pallier   nouveau my_packag...
814
815
816
    doctest.testmod()


b999fd50   Etienne Pallier   Nouvelle version ...
817
818
819
820
821
822
# """
# =================================================================
#     Main function (execution)
# =================================================================
# """

61165321   Etienne Pallier   nouveau my_packag...
823
if __name__ == "__main__":
b999fd50   Etienne Pallier   Nouvelle version ...
824
    """Comment on Main function execution"""
61165321   Etienne Pallier   nouveau my_packag...
825
    main()