Blame view

doc/code_style/my_package1/my_module1.py 19.6 KB
61165321   Etienne Pallier   nouveau my_packag...
1
2
#!/usr/bin/env python3

b999fd50   Etienne Pallier   Nouvelle version ...
3
4
5
6
7
8
"""
=================================================================
    MODULE general Comment

    This file conforms to the Sphinx Napoleon syntax :
    https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html
1b109b72   Etienne Pallier   New version of th...
9
10
11
12
13
14
15
16
17
18

    VERSION 17.02.2022

    Changes :

    - added new type annotation : Literal
    
    - added new types : NamedTuple, Dataclass, Enum, TypedDict
    
    - added custom and derived Exceptions
b999fd50   Etienne Pallier   Nouvelle version ...
19
20
=================================================================
"""
c5fb1b6a   Etienne Pallier   new my_package1.m...
21

b999fd50   Etienne Pallier   Nouvelle version ...
22
# This import MUST BE at the very beginning of the file (or syntax error...)
61165321   Etienne Pallier   nouveau my_packag...
23
24
from __future__ import annotations

b999fd50   Etienne Pallier   Nouvelle version ...
25

61165321   Etienne Pallier   nouveau my_packag...
26
# TODO :
61165321   Etienne Pallier   nouveau my_packag...
27
28
# - exception (custom)
# - dataclass
b999fd50   Etienne Pallier   Nouvelle version ...
29
30
# - NamedTuple
# - Enum
61165321   Etienne Pallier   nouveau my_packag...
31
32


97a4003f   Etienne Pallier   nouveau my_packag...
33
34
35
36
37
# '''
# =================================================================
#     PACKAGES IMPORT
# =================================================================
# '''
61165321   Etienne Pallier   nouveau my_packag...
38

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

1b109b72   Etienne Pallier   New version of th...
41
42
43
from typing import Dict, List, Tuple, Sequence, Any, TypeVar, Union, Callable, Literal
import typing

61165321   Etienne Pallier   nouveau my_packag...
44
45
import platform
from datetime import date
c5fb1b6a   Etienne Pallier   new my_package1.m...
46
import random
61165321   Etienne Pallier   nouveau my_packag...
47

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

b999fd50   Etienne Pallier   Nouvelle version ...
50
51
52
53
# 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...
54
#    DCCNotFoundException, UnknownGenericCmdException, UnimplementedGenericCmdException, UnknownNativeCmdException
b999fd50   Etienne Pallier   Nouvelle version ...
55
# )
61165321   Etienne Pallier   nouveau my_packag...
56

61165321   Etienne Pallier   nouveau my_packag...
57

97a4003f   Etienne Pallier   nouveau my_packag...
58
59
60
61
62
# '''
# =================================================================
#     GENERAL MODULE CONSTANTS & FUNCTIONS DEFINITIONS
# =================================================================
# '''
61165321   Etienne Pallier   nouveau my_packag...
63

b999fd50   Etienne Pallier   Nouvelle version ...
64
65
66
#
# - (General) Module level Constants
#
61165321   Etienne Pallier   nouveau my_packag...
67
68
69
70
71
72

DEBUG = False

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


97a4003f   Etienne Pallier   nouveau my_packag...
73
#
b999fd50   Etienne Pallier   Nouvelle version ...
74
# - (General) Module level Functions
97a4003f   Etienne Pallier   nouveau my_packag...
75
#
61165321   Etienne Pallier   nouveau my_packag...
76

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

b999fd50   Etienne Pallier   Nouvelle version ...
79
def general_function_that_returns_a_float(
1b109b72   Etienne Pallier   New version of th...
80
    arg_a: int, arg_b: str | int, arg_c: float = 1.2, arg_d: bool = True
b999fd50   Etienne Pallier   Nouvelle version ...
81
) -> float:
1b109b72   Etienne Pallier   New version of th...
82
    """This function illustrates Typehint 'Union' (or '|')
61165321   Etienne Pallier   nouveau my_packag...
83
84
85

    Args:
        arg_a: the path of the file to wrap
1b109b72   Etienne Pallier   New version of th...
86
        arg_b: instance to wrap
61165321   Etienne Pallier   nouveau my_packag...
87
88
89
90
91
92
93
94
95
96
        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...
97
98
99
100
101
102
103
104

    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 ...
105
    """
61165321   Etienne Pallier   nouveau my_packag...
106
107
108
109
110
111
112
113
114

    # comment on a
    a = 1

    # comment on b
    b = 2

    return 3.5

61165321   Etienne Pallier   nouveau my_packag...
115

1b109b72   Etienne Pallier   New version of th...
116

b999fd50   Etienne Pallier   Nouvelle version ...
117
118
119
120
121
122
# - 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...
123
124
125
126
127

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

b999fd50   Etienne Pallier   Nouvelle version ...
129
130
131
132
133
    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...
134

b999fd50   Etienne Pallier   Nouvelle version ...
135
    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...
136

b999fd50   Etienne Pallier   Nouvelle version ...
137
138
139
140
141
142
143
144
145
146
147
148
149
    >>> 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...
150

c5fb1b6a   Etienne Pallier   new my_package1.m...
151
def square(elems: Sequence[float]) -> List[float]:
b999fd50   Etienne Pallier   Nouvelle version ...
152
153
154
    """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...
155

c5fb1b6a   Etienne Pallier   new my_package1.m...
156
157
158
159
    Usage:

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

c5fb1b6a   Etienne Pallier   new my_package1.m...
161
162
    >>> square( (1,2,3) )
    [1, 4, 9]
b999fd50   Etienne Pallier   Nouvelle version ...
163
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
164

b999fd50   Etienne Pallier   Nouvelle version ...
165
    return [x ** 2 for x in elems]
c5fb1b6a   Etienne Pallier   new my_package1.m...
166
167


b999fd50   Etienne Pallier   Nouvelle version ...
168
# - Typehint : TypeAlias
c5fb1b6a   Etienne Pallier   new my_package1.m...
169

c5fb1b6a   Etienne Pallier   new my_package1.m...
170
171
172
Card = Tuple[str, str]
Deck = List[Card]

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

c5fb1b6a   Etienne Pallier   new my_package1.m...
176
177

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

    Create a new deck of 52 cards
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
182
183
184
185
186
187
188
    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 ...
189
190
191
    """This function (and the previous 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
199
200
201
202
203
204

    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 ...
205
# - Typehint : Generics avec Sequence, Any, TypeVar
c5fb1b6a   Etienne Pallier   new my_package1.m...
206
207

def choose_from_list_of_Any_returns_a_Any(items: Sequence[Any]) -> Any:
b999fd50   Etienne Pallier   Nouvelle version ...
208
209
210
211
    """This function illustrates Typehint 'Generics'

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


b999fd50   Etienne Pallier   Nouvelle version ...
215
216
217
T = TypeVar("T")


c5fb1b6a   Etienne Pallier   new my_package1.m...
218
def choose_from_list_of_a_specific_type_returns_same_type(items: Sequence[T]) -> T:
b999fd50   Etienne Pallier   Nouvelle version ...
219
220
221
    """This function illustrates Typehint 'Generics'

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

    T = TypeVar("T")
b999fd50   Etienne Pallier   Nouvelle version ...
224
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
225
226
227
    return random.choice(items)


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

c5fb1b6a   Etienne Pallier   new my_package1.m...
230

b999fd50   Etienne Pallier   Nouvelle version ...
231
232
233
234
235
236
237
238
239
240
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...
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256

    => 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)
b999fd50   Etienne Pallier   Nouvelle version ...
257
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
258
259
260
261

    return random.choice(items)


b999fd50   Etienne Pallier   Nouvelle version ...
262
# - Typehint : Callable
c5fb1b6a   Etienne Pallier   new my_package1.m...
263
264

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


b999fd50   Etienne Pallier   Nouvelle version ...
268
269
270
271
272
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...
273
274
275
276
277
    Usage:

    >>> do_twice(create_greeting, "Hello", "Jekyll", 1)
    Hello Jekyll 1
    Hello Jekyll 1
b999fd50   Etienne Pallier   Nouvelle version ...
278
    """
c5fb1b6a   Etienne Pallier   new my_package1.m...
279
280
281
282
    print(func(arg1, arg2, arg3))
    print(func(arg1, arg2, arg3))


1b109b72   Etienne Pallier   New version of th...
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# - Typehint : typing.Literal (new in 3.8)

def validate_simple(data: Any) -> Literal[True]:  
    """This function illustrates Typehint 'Literal' (new in 3.8)
    
    => 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:
    
    OK :

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

    Error :
    
    >>> open_helper('/other/path', 'typo')  
    """

    pass


c5fb1b6a   Etienne Pallier   new my_package1.m...
317
318
# '''
#    *******************************
b999fd50   Etienne Pallier   Nouvelle version ...
319
#      CUSTOM EXCEPTIONS CLASSES
c5fb1b6a   Etienne Pallier   new my_package1.m...
320
321
322
323
324
325
#    *******************************
#    See https://docs.python.org/3/tutorial/errors.html
# '''


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

61165321   Etienne Pallier   nouveau my_packag...
328
329
330
    pass


c5fb1b6a   Etienne Pallier   new my_package1.m...
331
class UnknownGenericCmdArgException(Exception):
b999fd50   Etienne Pallier   Nouvelle version ...
332
    """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...
333
334
335
336
337
338
339
340
341
342

    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 ...
343
344
    """Raised when a NATIVE command name is not recognized by the controller"""

c5fb1b6a   Etienne Pallier   new my_package1.m...
345
346
347
348
349
    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs)


class UnimplementedGenericCmdException(Exception):
b999fd50   Etienne Pallier   Nouvelle version ...
350
351
    """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...
352
353
354
355
    def __str__(self):
        return f"({type(self).__name__}): Device Generic command has no implementation in the controller"


1b109b72   Etienne Pallier   New version of th...
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
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
class MyImprovedException(Exception):
    """Improved Exeption class with predefined list of standard error messages, and optional specific message
    
    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):
        #super().__init__(error_msg)
        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:
    
    >>> 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"

'''
try:
    print("doing something dangerous...")
    raise MyOwnDerivedException(MyOwnDerivedException.ERROR_MISSING_PARAM)
except MyOwnDerivedException as e:
    print(e)
'''


61165321   Etienne Pallier   nouveau my_packag...
448
449
# '''
# =================================================================
b999fd50   Etienne Pallier   Nouvelle version ...
450
#     GENERAL CLASSES
61165321   Etienne Pallier   nouveau my_packag...
451
452
# =================================================================
# '''
c5fb1b6a   Etienne Pallier   new my_package1.m...
453
454
455
456
457
458
459
460
461
462


class MySuperClass1:
    pass


class MySuperClass2:
    pass


b999fd50   Etienne Pallier   Nouvelle version ...
463
464
465
466
467
# '''
# =================================================================
#     - CLASS MySimpleClass
# =================================================================
# '''
c5fb1b6a   Etienne Pallier   new my_package1.m...
468

61165321   Etienne Pallier   nouveau my_packag...
469
class MySimpleClass(MySuperClass1, MySuperClass2):
b999fd50   Etienne Pallier   Nouvelle version ...
470
    """a Class with multi-inheritance
61165321   Etienne Pallier   nouveau my_packag...
471
472
473
474

    blabla

    blabla
b999fd50   Etienne Pallier   Nouvelle version ...
475
    """
61165321   Etienne Pallier   nouveau my_packag...
476
477

    #
c5fb1b6a   Etienne Pallier   new my_package1.m...
478
    # Class attributes
61165321   Etienne Pallier   nouveau my_packag...
479
480
481
    #

    names: List[str] = ["Guido", "Jukka", "Ivan"]
b999fd50   Etienne Pallier   Nouvelle version ...
482
    """ List is mutable"""
61165321   Etienne Pallier   nouveau my_packag...
483
484

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

    options: Dict[str, bool] = {"centered": False, "capitalize": True}
b999fd50   Etienne Pallier   Nouvelle version ...
488
    """ Dict (is mutable) """
61165321   Etienne Pallier   nouveau my_packag...
489
490
491

    my_attr1: dict = {}
    current_file = None
61165321   Etienne Pallier   nouveau my_packag...
492
493

    #
c5fb1b6a   Etienne Pallier   new my_package1.m...
494
    # Class methods
61165321   Etienne Pallier   nouveau my_packag...
495
496
497
    #

    def __init__(self, a: int, b: float) -> None:
b999fd50   Etienne Pallier   Nouvelle version ...
498
        """
61165321   Etienne Pallier   nouveau my_packag...
499
500
501
502
        La methode __init__ doit toujours retourner "None"

        Args:
            a: blabla
b999fd50   Etienne Pallier   Nouvelle version ...
503
        """
61165321   Etienne Pallier   nouveau my_packag...
504
505
506
        c = 1
        d = 2

61165321   Etienne Pallier   nouveau my_packag...
507
    def __str__(self) -> str:
b999fd50   Etienne Pallier   Nouvelle version ...
508
        """
61165321   Etienne Pallier   nouveau my_packag...
509
        La methode __str__ doit toujours retourner "str"
b999fd50   Etienne Pallier   Nouvelle version ...
510
        """
61165321   Etienne Pallier   nouveau my_packag...
511
512
513
        return "toto"

    def my_method2(self, a: int, b: float) -> None:
b999fd50   Etienne Pallier   Nouvelle version ...
514
        """Method that returns nothing"""
61165321   Etienne Pallier   nouveau my_packag...
515
516
517
518
519
520
        a = 1
        b = 2


# '''
# =================================================================
b999fd50   Etienne Pallier   Nouvelle version ...
521
#     - CLASS Person
61165321   Etienne Pallier   nouveau my_packag...
522
523
524
525
# =================================================================
# '''

class Person:
b999fd50   Etienne Pallier   Nouvelle version ...
526
    """Class to create a person, in several ways (several Factory methods)
61165321   Etienne Pallier   nouveau my_packag...
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560

    => 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...
561
562
    @classmethod
    def fromBirthYear(cls, name: str, year: int) -> Person:
b999fd50   Etienne Pallier   Nouvelle version ...
563
564
        """A class method to create a Person object by birth year
        
c5fb1b6a   Etienne Pallier   new my_package1.m...
565
        NB : return type 'Person' is possible because of: 'from __future__ import annotations'
b999fd50   Etienne Pallier   Nouvelle version ...
566
        """
61165321   Etienne Pallier   nouveau my_packag...
567
568
        return cls(name, date.today().year - year)

61165321   Etienne Pallier   nouveau my_packag...
569
570
    @classmethod
    def twin(cls, name: str, p: Person) -> Person:
b999fd50   Etienne Pallier   Nouvelle version ...
571
        """A class method to create a Person object from another"""
61165321   Etienne Pallier   nouveau my_packag...
572
573
        return cls(name, p.age)

61165321   Etienne Pallier   nouveau my_packag...
574
575
    @staticmethod
    def isAdult(age: int):
b999fd50   Etienne Pallier   Nouvelle version ...
576
        """A static method to check if a Person is adult or not"""
61165321   Etienne Pallier   nouveau my_packag...
577
578
579
580
581
        return age > 18


# '''
# =================================================================
1b109b72   Etienne Pallier   New version of th...
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
#     - 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:
    
    1) Here we use typing.NamedTuple :
    
    >>> 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 :
    
    >>> 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/

   
    Usage:
    
    a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK

    b: Point2D = {'x': 1, 'y': 2}                   # KO (missing label)
    
    c: Point2D = {'z': 3, 'label': 'bad'}           # KO (z not defined)
    
    d: Point2D = {}                                 # KO (missing x, y, label)

    
    Definition (other possibilities):
    
    Point2D = TypedDict('Point2D', x=int, y=int, label=str)
    
    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'
    }



# '''
# =================================================================
#     - CLASS Position
# =================================================================
# '''

# @dataclass : shortcut for class definition

from dataclasses import dataclass, field


@dataclass
class Position:
    """@dataclass

    Class to illustrate Data Classes (@dataclass)
    
    See: https://realpython.com/python-data-classes
    
    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 : 
    
    - __init__() (with self.x = x, self.y = y, ...)
    
    - __repr()__
    
    - __eq()__

    - order, sort, immutable or not (frozen=True), ...
    
    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
    """
   
    name: str
    lon: float
    lat: float = 0.0 # with default value


@dataclass
class PlayingCard:
    """@dataclass
    
    Class to illustrate Data Classes (@dataclass)
    """
    rank: str
    suit: str


@dataclass
class Deck:
    """@dataclass
    
    Class to illustrate Data Classes (@dataclass)

    Usage:

    >>> queen_of_hearts = PlayingCard('Q', 'Hearts')
    
    >>> ace_of_spades = PlayingCard('A', 'Spades')
    
    >>> two_cards = Deck([queen_of_hearts, ace_of_spades])
    """
    cards: List[PlayingCard]


@dataclass
class Cmd:
    """@dataclass
    
    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'
    params: Dict[str, str] = field(default_factory=dict)  # equivalent to "= {}" which is not allowed
    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...
789
790
791
792
#    Main function (definition)
# =================================================================
# '''

61165321   Etienne Pallier   nouveau my_packag...
793
def main() -> None:
b999fd50   Etienne Pallier   Nouvelle version ...
794
    """Comment on Main function definition"""
61165321   Etienne Pallier   nouveau my_packag...
795
796
    a = 1
    b = 2
b999fd50   Etienne Pallier   Nouvelle version ...
797
    c = a + b
61165321   Etienne Pallier   nouveau my_packag...
798

b999fd50   Etienne Pallier   Nouvelle version ...
799
800
    e = general_function_that_returns_a_tuple_of_3_elem(c="toto", a=1, b=2)
    # print(e)
61165321   Etienne Pallier   nouveau my_packag...
801
802

    import doctest
b999fd50   Etienne Pallier   Nouvelle version ...
803

61165321   Etienne Pallier   nouveau my_packag...
804
805
806
    doctest.testmod()


b999fd50   Etienne Pallier   Nouvelle version ...
807
808
809
810
811
812
# """
# =================================================================
#     Main function (execution)
# =================================================================
# """

61165321   Etienne Pallier   nouveau my_packag...
813
if __name__ == "__main__":
b999fd50   Etienne Pallier   Nouvelle version ...
814
    """Comment on Main function execution"""
61165321   Etienne Pallier   nouveau my_packag...
815
    main()