You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/python/classes.md
+6-3Lines changed: 6 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -8,14 +8,17 @@ sidebar_label: Classes
8
8
9
9
* Avoid inbuilt names.
10
10
* Classes names should always be `PascalCase`. i.e. `MyClass`
11
-
* Use [abstract containers](https://docs.python.org/3/library/collections.abc.html#module-collections.abc) if need to override datatypes.
12
-
+ If you must build datatypes based on inbuilt class use PascalCase. i.e. `MyDict(dict):`.
11
+
***Abstract Classes and Mixins**
12
+
+ Use [abstract containers](https://docs.python.org/3/library/collections.abc.html#module-collections.abc) if need to override datatypes.
13
+
- If you must build datatypes based on inbuilt class use PascalCase. i.e. `MyDict(dict):`.
14
+
+ Use [`abc`](https://docs.python.org/3/library/abc.html) if you need pure OOP style abstract classes. Use `NotImplementedError` exceptions with overrides.
15
+
+ mixin should be named with `Mixin` suffix such as `class LoginRequiredMixin` which can be used in multiple inheritance.
13
16
* Describe the class responsibility in name.
14
17
* Custom Exceptions should always be named ending with `Error` i.e. `MyCustomError`
-[reStructured Text Docstrings](http://docutils.sourceforge.net/rst.html) (Seen in many inbuilt python libraries.)
131
132
-[Numpy Docstrings](https://numpydoc.readthedocs.io/en/latest/format.html) (**Recommended for AI projects**)
132
133
133
134
@@ -193,7 +194,7 @@ to check that your docstrings render correctly
193
194
194
195
### Google Docstrings (recommended)
195
196
196
-
```python3
197
+
```python
197
198
198
199
"""Example Google style docstrings.
199
200
@@ -496,9 +497,12 @@ class ExampleClass:
496
497
497
498
### ReStructured Text Doc strings
498
499
499
-
Here are few examples of docstrings to get you started
500
+
You can see this kind of docstring especially in python libraries.
501
+
Please use **Google** style as they are more readable.
502
+
503
+
##### Examples:
500
504
501
-
```python3
505
+
```python
502
506
"""The method below prints a given string twice
503
507
504
508
The print method has been called twice for
@@ -514,12 +518,8 @@ def print_twice(param1):
514
518
print(param1)
515
519
516
520
returnlen(param1)
517
-
```
518
521
519
-
The following shows type definition on the same line.
520
-
521
-
```python3
522
-
"""The method below prints a given string twice
522
+
"""The method below prints a given string twice. This is for type annotation.
523
523
524
524
The print method has been called twice for
525
525
implementing this method
@@ -528,13 +528,84 @@ implementing this method
528
528
:return: Length of the input string
529
529
:rtype: int
530
530
"""
531
-
def print_twice(param1):
531
+
defprint_twice(param1: str) -> int:
532
532
print(param1)
533
533
print(param1)
534
534
535
535
returnlen(param1)
536
536
```
537
537
538
+
## Doctests
539
+
:::caution
540
+
While this should not be used for all checks and [testing](testing.md) should be followed. They can be used for simple parameter checking. i.e. some default case like module level doctest in example below.
541
+
542
+
They can be used with [pytest](https://docs.pytest.org/en/latest/doctest.html) as well.
543
+
:::
544
+
545
+
Python provides tests through docstrings which can be leveraged by [doctests](https://docs.python.org/3/library/doctest.html).
546
+
547
+
Example
548
+
```python
549
+
"""
550
+
This is the "example" module.
551
+
552
+
The example module supplies one function, factorial(). For example,
553
+
554
+
>>> factorial(5)
555
+
120
556
+
"""
557
+
558
+
deffactorial(n):
559
+
"""Return the factorial of n, an exact integer >= 0.
560
+
561
+
>>> [factorial(n) for n in range(6)]
562
+
[1, 1, 2, 6, 24, 120]
563
+
>>> factorial(30)
564
+
265252859812191058636308480000000
565
+
>>> factorial(-1)
566
+
Traceback (most recent call last):
567
+
...
568
+
ValueError: n must be >= 0
569
+
570
+
Factorials of floats are OK, but the float must be an exact integer:
*`Exception` handling is a must and should be mitigated.
10
10
* Do not use bare `except` or `except Exception` which catches all the exception.
11
11
- Always be specific on exception. E.g. catch only `FileNotFoundError` if you are say moving a file.
12
-
* User Defined Exceptions:
12
+
***User Defined Exceptions**:
13
13
- Write your custom error only when your error is not described or fulfilled by [internal exceptions](https://docs.python.org/3/library/exceptions.html).
14
14
- Create custom `Exception` class primarily suffixing it with `Error` such as `MyCustomError(Exception)` and use it.
15
15
- Always use `Exception` as your parent class for user defined exceptions. Donot use `BaseException`.
16
16
* Add traceback to your mitigation. i.e. either `logging` or mails. Donot `pass`.
17
17
* The `try` block should be specific to desired exception. Donot use huge code chunk in `try`. Use `else` if needed.
18
+
```python
19
+
try:
20
+
value =int(some_str)
21
+
exceptValueError: # when not using exception object
22
+
WHEN some_str ISnot valid as value.
23
+
exceptTypeError:
24
+
WHEN some_str ISOTHERTYPE such as [], ()
25
+
else: #can be avoided if exceptions are handled and returned. This is in context to try block.
26
+
DOSOMETHINGWITHVALUE
27
+
28
+
try:
29
+
value =int(some_str)
30
+
except (ValueError, TypeError) as error:
31
+
HANDLEBOTH exception and use exception object
32
+
else: # If needed
33
+
do something when try succeeds.
34
+
finally:
35
+
codebase to run anyway
36
+
```
37
+
*`finally` can be used if you need to run the block whatever the case. `context` can be used in many cases to avoid `finally`.
38
+
*`sys.exc_info` and [`traceback`](https://docs.python.org/3/library/traceback.html) can be used for traceback.
39
+
* Please read [this](https://cosmicpercolator.com/2016/01/13/exception-leaks-in-python-2-and-3/) on exceptions handling internals and leaks when referencing exceptions.
Copy file name to clipboardExpand all lines: docs/python/general.md
+29-12Lines changed: 29 additions & 12 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -23,34 +23,51 @@ sidebar_label: General Coding Guidelines
23
23
- Try to use parent namespace for actions. i.e. `import sys: sys.path` rather that `from sys import path`
24
24
- Never use `import *` i.e. `from MODULE import *`
25
25
- use namespace whenever possible. Use `as SOMEOTHERNAMESPACE` for collision of namespace
26
-
* Use `else: #nobreak` if you are using `else` with loops that has `break`.
26
+
* If you are using `else` with loops that has `break`. Just comment `#nobreak` for reference as it is for that usage. See [this](http://python-notes.curiousefficiency.org/en/latest/python_concepts/break_else.html) for some clarity.
27
+
```python
28
+
for each in each_collection:
29
+
if condition:
30
+
break
31
+
else: #nobreak
32
+
ELSELOGIC
33
+
34
+
whileTrue:
35
+
if condition:
36
+
break
37
+
else: #nobreak
38
+
ELSELOGIC
39
+
```
27
40
* Use `pathlib`for path related use case rather than `os.path`
28
41
* Use `mypy`andtype annotation when possible fortype safe code.
29
-
*`Docker` can be used for deployment. Use `python` images for [docker](https://hub.docker.com/_/python).
42
+
*`Docker` can be used for deployment. Use `python` images for [`docker`](https://hub.docker.com/_/python).
30
43
* Use `generators`and`yield` instead of data structures for high streams of data.
31
-
* Use `itertools`, `functools` for utilities and `collection` for data structures.
44
+
* Use `itertools`, `functools`for utilities and`collections`for data structures.
32
45
* Use `dataclasses`if available. Go for`attrs` library if`dataclass`isnot present.
33
-
* Use `is not` and `is` for `None`, `True` and `False` specific check only. If most cases truthy and falsy can be checked with if `VARNAME:`.
46
+
* Use `isnot`and`is`for`None`, `True`and`False` specific check only. If most cases truthy and falsy can be checked with`ifVARNAME:`.
34
47
* Strings:
35
-
- Adhere to one quote practice. Double quote is recommended. Python doesnot differentiate between **'** or **"**.
48
+
- Adhere to one quote practice. Double quote is recommended. Python doesnot differentiate between **'** or **"**. This may be controlled by `formatter` used as well.
36
49
- Should be interpolated with either [fstring](https://www.python.org/dev/peps/pep-0498/) or`.format` methods. Try to avoid `%`.
37
50
+`format_map` should be used for key mapped formatting.
38
51
-`+` can be used for direct string concatenation. Use `join` method for concatenation instead of `+=` when iterating.
39
52
* Use `context` whenever supported especially for io related closing actions.
40
53
- i.e. `with` statement when supported.
41
54
- Always remember to close on exit. i.e. if you open the file`close` on `finally`or better use `with`or`contextlib.closing`.
42
-
* While `python` is an OOP, you can always choose `functions` and `modules` over `class` if there is only one `object` to be created.
43
-
* Use `property` setter when writing OOP and you need readonly attributes.
55
+
***OOP**
56
+
- While `python`is an OOP, you can always choose `functions`and`modules` over `class`if there is only one `object` to be created like `Singletons`.
57
+
- Use [`abc`](https://docs.python.org/3/library/abc.html) if you need abstraction. Mixins are more famous in python due to multiple inheritance.
58
+
- Use `property` setter getter only when you need readonly attributes. `__` variables can be used for some privacy.
59
+
- Use `super`for overrides and parent calls.
44
60
* Use `pdb`as debugger whenever required.
45
61
* Multi-threading can be especially used when we have io bound and network bound multiple operation. Multiprocessing can be used to use multiple cores.
46
62
- Recommended module is`concurrent.futures`in most cases. If lower level APIis needed there is always `threading`and`multiprocessing` module.
47
-
- Be very carefult on threads and locks, so always discuss what you are doing.
63
+
- Be very carefult on threads and locks, so always discuss what you are doingas it may not always be optimized.
48
64
- Use `asyncio`forIO bound async flow. This is something new and constantly changing in`python`.
49
65
* Recommended third party modules:
50
66
- For Relational Database:
51
-
+ Use `sqlalchemy`[core](https://docs.sqlalchemy.org/en/13/core/) for DB abstraction. This is particularly helpful when doing testing in `sqlite` and some other database for production. Also, for query consistency.
52
-
+ Use `sqlalchemy`[ORM](https://docs.sqlalchemy.org/en/13/orm/) or framework supported ORM when using specific framework.
53
-
+ Use DBAPI drivers such as `pyodbc`, `sqlite`, `mysqlclient` etc only when you donot want `sqlalchemy` dependency or when you are very performance conscious. While the API will be mostly compatible for this as python has DBAPI specification. Parameters binding and some methods may be incompatible or unavailable.
67
+
+ Use `sqlalchemy` [core](https://docs.sqlalchemy.org/en/13/core/) forDB abstraction. This is particularly helpful when doing testing in`sqlite`and some other database for production. Also, for query and parameters consistency.
68
+
+ Use `sqlalchemy` [ORM](https://docs.sqlalchemy.org/en/13/orm/) or framework supported **ORM** when using specific framework.
69
+
+ Use DBAPI drivers such as`pyodbc`, `sqlite`, `mysqlclient` etc only when you donot want `sqlalchemy` dependency or when you are very performance conscious. While the API will be mostly compatible for this as python has DBAPI specification. Parameters binding and some methods may be incompatible or unavailable. **sqlalchemy core is recommended.**
54
70
-`requests`for http request stuff.
55
-
-`attrs` for data oriented objects and class.
71
+
+`aiohttp`or`httpx` are also good.
72
+
-`attrs`for data oriented objects and classes design.
-**WARN**: log user security and other warnings that may require attention or may need to be avoided.
14
14
-**ERROR**: errors in programs.
15
15
-**CRITICAL**: blocking issues or immediate attention issues.
16
-
***ERROR and CRITICAL** levels should be mitigated and informed.
17
16
*`logger` is used for naming single logger object. Use `NAME_logger` name for more than one logger when required.
18
17
* It is singleton and single threaded by default for given name of the logger. Can be [non-blocking](https://docs.python.org/3/howto/logging-cookbook.html#dealing-with-handlers-that-block) if required.
19
-
*[Logging Cookbook](https://docs.python.org/3/howto/logging-cookbook.html) for reference.
20
-
* Always use `exception` method rather than `error` method of `logger` object to log traceback when catching exceptions.
18
+
* See [Logging Cookbook](https://docs.python.org/3/howto/logging-cookbook.html) for reference.
19
+
***ERROR and CRITICAL** levels should be mitigated and informed.
20
+
- Always use `exception` method rather than `error` method of `logger` object to log traceback when catching exceptions.
0 commit comments