I've been using these two functions to write my CSV headers:
def get_csv_headers():
return ['col 1', 'col 2', 'col 3', 'col 4']
def write_csv_headers():
with open(csv_path, 'w', newline='', encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=csv_headers)
writer.writeheader()
csv_headers = get_csv_headers()
write_csv_headers()
However, I recently learned about *args
and **kwargs
(I'm a Python autodidact) and modified my code to:
def write_csv_headers(*args):
with open(csv_path, 'w', newline='', encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=[*args])
writer.writeheader()
csv_headers = write_csv_headers('col 1', 'col 2', 'col 3', 'col 4')
I'm trying to learn more about Pythonic syntax and apply Python best practices. Which one is better?
CodePudding user response:
Neither. You shouldn't hard-code the header names, it's good to use a function, like in the first version.
But you shouldn't use a global variable, you should pass the header names as an argument, as in the second version.
There's no need to use *args
for this, it can be an ordinary parameter.
def get_csv_headers():
return ['col 1', 'col 2', 'col 3', 'col 4']
def write_csv_headers(path, headers):
with open(path, 'w', newline='', encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=headers)
writer.writeheader()
csv_headers = get_csv_headers()
write_csv_headers(csv_path, csv_headers)
CodePudding user response:
*args and **kwargs are usually more for passing the args and kwargs along to another function down the road. In this case you're using the args directly. I think the pythonic way would be
headers = get_csv_headers()
write_csv_headers(headers)
CodePudding user response:
If function get_csv_headers returns a list I think it is better to first create a variable to get data from funtion and then pass it to second one as an arguments
code:
#let's assume that this func does some logic (like filtering) to get headers
def get_csv_headers():
#filter code
return ['col 1', 'col 2', 'col 3', 'col 4']
def write_csv_headers(pathDir:str,headersList:list):
with open(pathDir, 'w', newline='', encoding="utf-8") as f:
writer=csv.DictWriter(f, fieldnames=headersList)
writer.writeheader()
filtered_headers=get_csv_headers()
write_csv_headers(pathDir='path', headerList=filterd_headers)
#or
write_csv_headers(pathDir='path', headerList=get_csv_headers())