I have a python script with a generic method that calls functions for every line in a file. This method takes the function to be called as a parameter and arguments (optional) for this function. The problem is that some of the functions that it will call need parameters and others don't.
How would I go about doing this?
Code example:
def check_if_invalid_characters(line, *args):
# process word
def clean_words_with_invalid_characters():
generic_method(check_if_invalid_characters, *args)
def check_if_empty_line(line):
# process word
def clean_empty_lines():
generic_method(check_if_empty_line)
def generic_method(fun_name, *args):
with open("file.txt") as infile:
for line in infile:
if processing_method(line, *args):
update_temp_file(line)
clean_words_with_invalid_characters()
clean_empty_lines()
wouldn't an if ,else satisfy your needs? like this :
def whatever(function_to_call,*args):
if(len(arg)>0):
function_to_call(*args)
else:
function_to_call()
You can still pass empty *args to the function that doesn't need them...
If a function only calls another function then you can bypass it, don't you?
def check_if_invalid_characters(line, *args):
# process word using *args
print(args)
def check_if_empty_line(line, *args):
print(args)
# process word and don't use *args (should be empty)
def generic_method(processing_method, *args):
with open("file.txt") as infile:
for line in infile:
if processing_method(line, *args):
update_temp_file(line)
generic_method(check_if_invalid_characters, foo, bar)
generic_method(check_if_empty_line)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.