Feb-10-2018, 02:03 PM
what if both are specified?
redefinition of unused function
|
Feb-10-2018, 02:03 PM
what if both are specified?
You decide what the function will do with the parameters. I am giving you a way to take an action according to the parameter.
def func(something): if type(something) == str: # action elif type(something) == Object: # actionMaybe there are other ways but this is just an example. I am tired You want to do something according to the function's parameter type. Check the type.
Feb-10-2018, 04:05 PM
yeah but this is not a pythonic way, right? as others have mentioned
Hm! What does pythonic mean, then?
I do not know all built-in functions and modules. Perhaps there is a better way. As R. Hettinger says. I didn't read the previous posts very well. @Gribouillis mentioned it - from the functools module singledispatch.
Feb-10-2018, 06:48 PM
my bad, i was in class when reading the comments and wasn't careful. thanks for putting that forward. that's what i needed actually
(Feb-10-2018, 06:00 PM)wavic Wrote: Hm! What does pythonic mean, then? def func(something): if isinstance(something, (int, float)): return something ** 2 elif isinstance(something, bytes): return something.decode(errors='IGNORE') elif isinstance(something, (list, tuple, dict)): return list(something) else: raise Exception('Input type not supported')I like the syntactic sugar of signledispatch. Now the same function with singledispatch: @singledispatch def func(something): raise Exception('Input type not supported') @func.register(float) @func.register(int) def _(something): return something ** 2 @func.register(bytes) def _(something): return something.decode(errors='IGNORE') @func.register(list) @func.register(tuple) @func.register(dict) @func.register(set) def _(something): return list(something)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
EDIT: don't read on. i forgot self.
since i needed a member function, i found this on the internet: def method_dispatch(func): dispatcher = singledispatch(func) def wrapper(*args, **kwargs): return dispatcher.dispatch(args[1].__class__)(*args, **kwargs) wrapper.register = dispatcher.register update_wrapper(wrapper, func) return wrapperthen: @method_dispatch def do_work(self, info): pass @call.register(type1) def _(self, param): return do_work(param) @call.register(str) def _(self, param): # do workas you can see i'm calling an overload from another one, but i get "undefined variable" on that call. how should i call it? |
|
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
Uninstall unused COM ports windows 10 | adbrooker | 1 | 2,056 |
Sep-22-2021, 03:16 AM Last Post: Larz60+ |
|
redefinition of a method in a class: pylint warning | kboo | 1 | 4,280 |
Feb-13-2018, 11:21 AM Last Post: buran |