Skip to content

Instantly share code, notes, and snippets.

@kchawla-pi
Last active August 3, 2022 16:19
Show Gist options
  • Save kchawla-pi/95950547222435bcd802016cd5800120 to your computer and use it in GitHub Desktop.
Save kchawla-pi/95950547222435bcd802016cd5800120 to your computer and use it in GitHub Desktop.
Clean Code Python: Code snippets for blog post "Writing Appreciable Python Code"
from pathlib import Path
text = Path(text_filepath).read_text()
image_data = Path(binary_filepath).read_bytes()
import os
text_filepath = os.path.join("user", "me", "somefile.txt")
with open(text_filepath) as fp:
text = fp.read()
print(text)
binary_filepath = os.path.join("user", "me", "some_image.jpg")
with open(binary_filepath, 'b') as fp:
image_data = # <read image data> from fp
print(image_data)
import os
text_filepath = os.path.join("user", "me", "somefile.txt")
fp = open(text_filepath)
text = fp.read()
print(text)
fp.close()
binary_filepath = os.path.join("user", "me", "some_image.jpg")
fp = open(binary_filepath, 'b')
image_data = <read image data> from fp
print(image_data)
fp.close()
def calc_relative_refractive_index(v1, v2):
...
return v1/v2
def calc_relative_refractive_index(light_velocity_1: float, light_velocity_2: float) -> float:
""" Calculate relative refractive index of light between 2 media.
Relative Refractive Index of Medium 1 with respect to medium 2 is the ratio of velocity of light in medium 1 and medium 2.
Arguments:
light_velocity_1 : Velocity of light in medium 1
light_velocity_2 : Velocity of light in medium 2
Returns:
Relative refractive index.
"""
...
return light_velocity_1 / light_velocity_2
def calc_relative_refractive_index(light_velocity_1:float, light_velocity_2: float):
""" Calculate relative refractive index between 2 media.
"""
...
return light_velocity_1/light_velocity_2
def calc_relative_refractive_index(light_velocity_1: float, light_velocity_2: float) -> float:
""" Calculate relative refractive index between 2 media.
Arguments:
light_velocity_1 : Velocity of light in medium 1
light_velocity_2 : Velocity of light in medium 2
Returns:
Relative refractive index.
"""
...
return light_velocity_1 / light_velocity_2
import os
basedir = "/user/me"
dirpath = os.path.join(basedir, "Documents", "datasets", "develop")
source_filepath = os.path.join(dirpath, "image_array.txt")
with open(source_filepath, 'r') as fp:
lines = fp.readlines()
...
destination_filepath = os.path.join(dirpath, "image.jpg")
with open(destination_filepath, 'wb') as fp:
fp.write(b"897689hiuh9")
from pathlib import Path
basedir = Path("/user/me")
dirpath = basedir / "Documents" / "datasets" / "develop"
# or
dirpath = basedir.joinpath("Documents", "datasets", "develop")
source_filepath = dirpath / "image_array.txt"
lines = source_filepath.read_text().splitlines()
...
destination_filepath = dirpath / "image.jpg"
destination_filepath.write_bytes(b"897689hiuh9")
final_list = list1 + list2 + list3
final_set = set1 + set2 + set3
final_dict = dict1 + dict2 + dict3
final_list = list1 + range(5) # -> Raises TypeError (does not work with generators).
final_list = [*list1, *list2, *list3]
final_tuple = (*tuple1, *tuple2, *tuple3)
final_set = set1 | set2 | set3 # Must be all sets
final_dict = dict1 | dict2 | dict3 # Must be all dicts
final_set = set1 | range(5) # -> Raises TypeError (does not work with generators).
final_list = [*list1, *list2, *list3]
final_tuple = (*tuple1, *tuple2, *tuple3)
final_set = {*set1, *set2, *set3}
final_dict = {**dict1, **dict2, **dict3}
final_list = [*list1, *range(5)] # Works with generators.
from typing import List, \
Optional, \
Union
total = a + \
b + \
c
long_text = "first" \
"second" \
"third"
from typing import (
List,
Optional,
Union,
)
total = (
a
+ b
+ c
)
long_text = ("first"
"second"
"third"
)
def corr(df, th, c):
...
def correlation(dataframe, thresh, cols_list):
...
from pandas import DataFrame
from typing import List, Optional
def drop_correlated_features(
data: DataFrame,
correlation_threshold: float,
subset_fields: Optional[List[str]] = None,
) -> DataFrame:
...
def drop_corr_cols(data, threshold, fields):
...
def drop_correlated_cols(data, threshold, fields):
...
Prefix Usage Context
_ Indicates protected function, method, variable to be used by our own code, but not directly by the end users.
__ Indicates private method, to be used only within its own class but not directly by other code, and certainly not users.
get_ Read data from an object (internal object, for files, prefers read_); do stuff, or not; and return the wanted object
read_ Read a file and return the data
make_ Create an object from a collection of different objects
set_ Set a something to some state or value. Does not return the value set, return error or success
to_ Transform a object type to another type
def fill_na_in_fields(data: DataFrame, fields: List[str]):
data[fields].fillna(0, inplace=True)
print(data.head())
return data
fill_na_in_fields(some_data, ["cost", "properties"])
from typing import List
from pandas import DataFrame
def fill_na_in_fields(data: DataFrame, fields: List[str]) -> DataFrame:
return data[fields].fillna(0)
filled_in_data = fill_na_in_fields(data=some_data, fields=["cost", "properties"])
print(filled_in_data.head())
def fill_na_in_fields(data: DataFrame, fields: List[str]):
data = data[fields].fillna(0)
return data
fill_na_in_fields(data=some_data, fields=["cost", "properties"])
from functools import partial
diff_extras_example_function = partial(example_function, some_data, fields=["cost", "properties"])
diff_extras_example_function(extra_field=None)
diff_extras_example_function(extra_field="area")
diff_extras_example_function(extra_field="agent")
diff_extras_example_function(extra_field="owner")
example_function(some_data, fields=["cost", "properties"], extra_field=None)
example_function(some_data, fields=["cost", "properties"], extra_field="area")
example_function(some_data, fields=["cost", "properties"], extra_field="agent")
example_function(some_data, fields=["cost", "properties"], extra_field="owner")
text_fragment_1 = "This is bad."
text_fragment_2 = "Using + is a computationally expensive."
text_fragment_3 = " It also forces one to add join spaces within the string fragments themselves."
text = text_fragment_1 + text_fragment_2 + text_fragment_3
text_fragment_1 = "This is good."
text_fragment_2 = "Easier to read and faster to compute."
text_fragment_3 = "Also, the fragments don't need the join spaces."
text = f"{text_fragment_1} {text_fragment_2} {text_fragment_3}"
a_string = "%s s-formatted %s string", arg1, arg2
text = "Avoid string interpolation using {}".format(format_method_text)
fstring_text = "f-string"
text = f"Use {fstring_text}."
import logging
logging.info(f"{arg1} f-formatted {arg2} string")
logging.info("%s s-formatted %s string" % (arg1, arg2)) # note the `%` after the string and before the args
logging.info("{} s-formatted {} string", arg1, arg2) # valid if logging is well configured (not recommended)
import logging
logging.info("%s s-formatted %s string", arg1, arg2) # note the `,` and NOT `%` after the string and before the args
def fill_na_in_fields(data, fields):
return data[fields].fillna(0)
filled_in_data = fill_na_in_fields(data=some_data, fields=["cost", "properties"])
print(filled_in_data.head())
filled_in_data = some_data[fields].fillna(0)
print(filled_in_data.head())
from typing import Sequence, Tuple
from pandas import DataFrame
def calc_anova(data: DataFrame, fields: Sequence[str]) -> Tuple[float, float]:
...
from typing import Optional, Union
def make_random_number(seed: Optional[int] = None) -> Union[int, float]:
""" Returns a random number of type int OR float"""
...
from typing import Sequence
from pandas import DataFrame
def calc_anova(data: DataFrame, fields: Sequence[str]) -> tuple[float, float]:
...
def make_random_number(seed: int | None = None) -> int | float:
""" Returns a random number of type int OR float"""
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment