Skip to content

Commit

Permalink
Add optimization and essentials
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrgredowski authored and pgred-orsted committed Sep 9, 2024
1 parent 3a9a7d9 commit 4a339e4
Show file tree
Hide file tree
Showing 24 changed files with 484 additions and 2 deletions.
1 change: 0 additions & 1 deletion .presentations/rust_python/plugin.js

This file was deleted.

1 change: 1 addition & 0 deletions .presentations/rust_python/rust_python.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ revealOptions:

</style>


## How Rust is speeding up Python (bindings and tooling)

"Rust and Python: A Match Made in Heaven\*" <!-- .element: class="fragment" data-fragment-index="1" -->
Expand Down
11 changes: 10 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,14 @@
"python.testing.pytestEnabled": true,
"python.linting.enabled": false,
"ruff.organizeImports": true,
"ruff.fixAll": true
"ruff.fixAll": true,
"ruff.lint.args": [
"--config",
"pyproject.toml"
],
"ruff.lint.enable": false,
"ruff.format.args": [
"--config",
"pyproject.toml"
]
}
Empty file.
5 changes: 5 additions & 0 deletions src/essentials/01_modules/00_module_as_file/common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def add_two_numbers(a, b):
return a + b

def subtract_two_numbers(a, b):
return a - b
8 changes: 8 additions & 0 deletions src/essentials/01_modules/00_module_as_file/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from .common import add_two_numbers
from .common import subtract_two_numbers

if __name__ == '__main__':
a = 1
b = 2
print(f"Add {a} and {b}: {add_two_numbers(a, b)}")
print(f"Subtract {a} and {b}: {subtract_two_numbers(a, b)}")
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from ._add import add_two_numbers # noqa: F401
from ._subtract import subtract_two_numbers # noqa: F401


Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def subtract_two_numbers(a, b):
return a - b
45 changes: 45 additions & 0 deletions src/essentials/01_modules/01_module_as_directory/common/add.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
def _add(a, b):
return a + b

def _check_if_positive(a):
...

def add_two_numbers(a, b):
_check_if_positive(a)
return _add(a, b)


class Calculator:
class _Adder:
def add(self, a, b):
return a + b
class Subtracter:
def subtract(self, a, b):
return a - b

class Config:
...

Calculator._Adder()
Calculator.Config()


quarter = 0.25

plot_size_multiplier = [0.5, 0.25, 0.25]

plot_size_multiplier[0]

plot_size_multiplier[1]

standard_plot_width = 1000

plot_2_size = standard_plot_width * plot_size_multiplier[1]
plot_2_size = 1000 * 0.25
plot_2_size = 250

#

time_for_timeout = 60 * 60 * 24 # 24 hours

timeout(86400)
11 changes: 11 additions & 0 deletions src/essentials/01_modules/01_module_as_directory/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from .common import add_two_numbers
from .common import subtract_two_numbers


from .common import add_two_numbers

if __name__ == '__main__':
a = 1
b = 2
print(f"Add {a} and {b}: {add_two_numbers(a, b)}")
print(f"Subtract {a} and {b}: {subtract_two_numbers(a, b)}")
87 changes: 87 additions & 0 deletions src/essentials/02_names/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# 1. Non-descriptive function names
def func():
pass

# 2. Overly abbreviated function names
def calc():
pass

# 3. Misleading function names
def get_data():
pass # But it actually updates the database

# 4. CamelCase function names (not recommended in Python)
def getData():
pass

def set_a_number():
pass

# 1. Non-descriptive class names
class MyClass:
pass

# 2. Overly abbreviated class names
class C:
pass

# 3. Misleading class names
class Manager:
pass # But it actually represents a single employee

# 4. CamelCase class names (not recommended in Python)
class MyFirstClass:
pass


# 1. Single-letter variable names
x = 10

diameter = 10

# 2. Overly abbreviated variable names
temp = 25

# 3. Misleading variable names
num = 'John' # When it should represent an integer

data = {}

# 4. Using reserved keywords as variable names
for_ = 5 # 'for' is a reserved keyword in Python

type_ = 123

__a = 1

## Other bad examples
flag = False # It's not clear what 'flag' is indicating.
use_database = True # It's indicating action, not a state.
red = True
x = 172800 # It's not clear what 'x' represents.

## Good examples
should_use_database = True
is_red = True
two_days = 60 * 60 * 24 * 2 # 2 days in seconds
timeout = two_days


class PositiveCalculator:


def _validate_number(self, number):
if number < 0:
raise ValueError("Number must be positive")

def add(self, a, b):
self._validate_number(a)
self._validate_number(b)
return a + b

def subtract(self, a, b):
return a - b

# 1.2.3
# 2.0.0

7 changes: 7 additions & 0 deletions src/essentials/03_more_of_names/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
flag = ...
use_database = ...
red = ...
x = ...


should_use_database
22 changes: 22 additions & 0 deletions src/essentials/03_more_of_names/bad.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
## Other bad examples
flag = False # It's not clear what 'flag' is indicating.
use_database = True # It's indicating action, not a state.
red = True
x = 172800 # It's not clear what 'x' represents.



def use_database():
database.use()
pass

def run_a_car():
pass

def should_run_a_car():

# use_database = True

def func(callable):
...

5 changes: 5 additions & 0 deletions src/essentials/03_more_of_names/good.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## Good examples
should_use_database = True
is_red = True
two_days = 60 * 60 * 24 * 2 # 2 days in seconds
timeout = two_days
6 changes: 6 additions & 0 deletions src/essentials/04_global_variables/00_data.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Country,Capital,CountryCode
Poland,Warsaw,PL
Denmark,Copenhagen,DK
Malaysia,Kuala Lumpur,MY
Germany,Berlin,DE
Spain,Madrid,ES
Empty file.
28 changes: 28 additions & 0 deletions src/essentials/04_global_variables/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import pathlib
import typing

from reader import read_csv
from divisions import get_divisions_for_country, print_divisions
from settings import settings



def main():
settings.print_app_title()

path_to_file = str(pathlib.Path(__file__).parent / "00_data.csv")
data = read_csv(path_to_file)
for row in data:
country_code = row.get("CountryCode")
if (country_code is None) or country_code in settings.skip_country_codes:
continue
divisions = get_divisions_for_country(country_code)
print_divisions(
country_name=row['Country'],
capital=row['Capital'],
divisions=divisions
)


if __name__ == '__main__':
main()
31 changes: 31 additions & 0 deletions src/essentials/04_global_variables/divisions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import argparse
import re
import httpx
import typing

def _get_url_for_country(country_code: str):
return f"https://rawcdn.githack.com/kamikazechaser/administrative-divisions-db/master/api/{country_code}.json"

def get_divisions_for_country(country_code: str):
return httpx.get(_get_url_for_country(country_code)).json()

def print_divisions(*, country_name: str, divisions: typing.List[str], capital: typing.Union[str, None] = None):
print("====================================")
capital_part = f" ({capital})" if capital else ""
print(f"Divisions for {country_name}{capital_part}:")
for division in divisions:
print(f"- {division}")
print("====================================")

argparser = argparse.ArgumentParser()

argparser.add_argument("--country", help="Country code to get divisions for", default="PL")
argparser.add_argument("--pretty", help="Pretty print the output", action="store_true")
args = argparser.parse_args()

divisions = get_divisions_for_country(args.country)

if args.pretty:
print_divisions(country_name=args.country, divisions=divisions)
else:
print(divisions)
16 changes: 16 additions & 0 deletions src/essentials/04_global_variables/reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import pathlib
import csv

def read_csv(path_to_file: str):
with open(path_to_file, mode='r') as file:
reader = csv.DictReader(file)
data = list(reader)

return data


path_to_file = str(pathlib.Path(__file__).parent / "00_data.csv")
print("====================================")
print(read_csv(path_to_file))
print("====================================")

15 changes: 15 additions & 0 deletions src/essentials/04_global_variables/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import dataclasses


@dataclasses.dataclass
class _AppSettings:
title: str
should_shout: bool = False
skip_country_codes: list = dataclasses.field(default_factory=list)

def print_app_title(self):
title = self.title.upper() if self.should_shout else self.title
print(title)


settings = _AppSettings(title="Divisions Finder", skip_country_codes=["DE"])
Empty file added src/optimization/__init__.py
Empty file.
Loading

0 comments on commit 4a339e4

Please sign in to comment.