Last active
October 9, 2019 06:24
-
-
Save gyli/31f43ce8ee189e274a421f80ad52f1fe to your computer and use it in GitHub Desktop.
Load parameters with default values in an elegant way in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
class CustomCSVReader: | |
_CSV_DEFAULT_PARS = { | |
"delimiter": ",", | |
"doublequote": True, | |
"escapechar": None, | |
"lineterminator": "\r\n", | |
"quotechar": '"', | |
"quoting": csv.QUOTE_MINIMAL, | |
"skipinitialspace": False, | |
"strict": False, | |
} | |
def __init__(self, csv_file: str, custom_csv_par: str, **kwargs): | |
""" | |
:param kwargs: passing any parameter of Python's csv.reader as keyword parameter | |
""" | |
self.custom_csv_par = custom_csv_par | |
# Load the default parameters for csv reader and update it with parameters passed in | |
# Then we will have full parameters of csv.reader with custom values if passed in and all default values | |
self.csv_pars = { | |
**self._CSV_DEFAULT_PARS, | |
**{k: kwargs[k] for k in set(kwargs).intersection(self._CSV_DEFAULT_PARS)}, | |
} | |
print("Reading CSV file with parameter:") | |
print(self.csv_pars) | |
csv.reader(csvfile, **self.csv_pars) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment