author:: Raimi Karim
url:: https://betterprogramming.pub/4-anti-patterns-in-python-a6d5023c8473
publish_date:: 2021-09-13
---
## Avoid docstrings for DRY code
and instead use it for something simple or concise to show the change that would be made where the data typing and code itself is self documenting
```python
def remove_special_chars (text: str) -> str:
"""
["hello world!\n"] →> ["hello world"]
"""
pass
```
## avoid dictionaries for read only data as they are mutable
use frozen dataclasses instead as they will also throw exceptions if you try to write to them
```python
from dataclasses import dataclass
@dataclass(frozen=True)
class Person:
name: str
age: int
country: str
```
## Strings instead of enums
rather than checking against strings, use [[enum]]'s to check against
```python
from enum import Enum
class SolverAlgorithm(Enum):
LBFGS = 0
SAGA = 1
SAG = 2
def fit(solver: SolverAlgorithm = SolverAlgorithm.LBFGS):
if solver == SolverAlgorithm.LBFGS:
pass
elif solver == SolverAlgorithm.SAGA:
pass
elif solver == SolverAlgorithm.SAG:
pass
else:
raise ValueError
```
## List comprehensions spanning multiple lines
indent longer conprehensions if the logic gets long and complex enough to justify this formatting:
```python
nested_list = [[1,2,3], [4,5,6], [7,8,9]]
new_list = []
for sub_list in nested_list:
if sum(sub_list) <= 6:
continue
for x in sub_list:
item = x if x > 4 else -1
new_list.append(item)
```