I konw your meaning, your solution is good, and my friend want to get a
method which can handle all cases not only tuple and list.
Without know where he wants to use this I’d be inclined to go something
like:
if isinstance(src, tuple):
return result if isinstance(result, tuple) else tuple(result)
if isinstance(src, list):
return result if isinstance(result, list) else list(result)
raise TypeError("src %s was neither tuple nor list" % type(src))
I’m just letting src
be your source object on which you want to base
your return type, and result
be whatever your function computed.
You could be slightly trickier and use:
return result if isinstance(result, list) else type(src)(result)
which might in turn lead to:
return (
result if isinstance(result, type(src))
else type(src)(result)
)
This assumes the src’s type can be initialised with the result as an
argument. If we’re dealing with lists and tuples and expect the result
to be a sequence or maybe iterable this will work, if src’s class does
not have a different style of __init__
method.
I think it’s a intersting question so that i give him a solution like
factory mode to get param’s type object’s new func to new a object,
and i know my solution is not good, i just want to konw more
interesting function regardless of practicality
I think the difficult part is initialising the return object i.e. how to
call your factory. You don’t know how to do that if src
might be any
type of object. If you presume it is a tuple or list or a subclass which
does not change __init__
, or a duck type which acts like a tuple or
list and has the same kind of __init__
then you’re ok.
I think the task is open ended enough that I would at least have a
nonclever version of the function which just returned a list (or a tuple
if that was natural) and a separate wrapper function which calls the
basic function then does the clever inversion:
def basefunc(src, ...):
... compute result, probably a list ...
return result
def sametype_func(src, ...):
result = basefunc(src, ...)
... convert result into the target src type ...
return converted_result
and that leads into what is a common pattern:
class Thing:
def __init__(self, ....):
.............
@classmethod
def from_list(cls, list_value:[list,tuple]):
return cls(args_to_init)
and you’d make args_to_init
from whatever was in list_value
. This
puts the class-specific knowledge of how to make a Thing
into the
Thing
class itself.
Then if you’re working with various classes, if they all provide their
own from_list
factory method you can just call:
return type(src).from_list(result)
to have the class itself convert your list-or-tuple into the right
object.
Cheers,
Cameron Simpson cs@cskk.id.au