Overload Methods in Python (Workarounds) -
a simplified version of problem: want write method in python takes in 1 parameter, either list of strings or custom object holds list of strings. return size of list. method user call want simple user (essentially don't want 2 methods doing same exact thing except single line of code , don't want import non python standard libraries)
i realize overloading not possible in python in java.
what way go this/what standard way? solutions have thought of are:
write 2 different methods. write 1 method 2 parameters , defaults, check defaults move accordingly. write 1 method 1 parameter, check kind of object passed in, move accordingly (not entirely sure if type checking possible)
from design perspective if statements each type of object want handle not seem great in long run, don't see other solutions (besides separate methods)
thank suggestions!
in python, use single dispatch function establish single method different implementations based on argument type (specifically, on type of first argument).
from functools import singledispatch @singledispatch def process_str_list(str_list): raise notimplementederror @process_str_list.register(list) def _(str_list): # process raw list of strings @process_str_list.register(mystrlistclass) def _(str_list) # process object
to invoke function, call process_str_list
raw list or object. type determination , implementation multiplexing takes place internally.
edit: wanted add pep introduced single dispatch says:
it common anti-pattern python code inspect types of received arguments, in order decide objects.
single dispatch pythonic way approach behavior.
Comments
Post a Comment