I need a function that changes the return type according to the conditions as follows.
def get_info(command):
if command == 'List':
result = [1,2,3,4,5]
elif command == 'Number':
result = 3
elif command == 'String':
result = 'string'
else:
print('command ({}) is not implemented'.format(command))
return result
print(get_info('list')))
print(get_info('number')))
print(get_info('string')))
The code above works fine.
I saw the following on the Internet.
Link: Returning more than one variable type from function call
In other words, if you do more than one Python return type, it will complicate subsequent processing It says, "It's not a good coding method," and instead, use error processing.
What should I do if each other type of return is a normal path rather than an error as above? Would it be better to make each case a separate function?
python return-type return
Hello :-)
That the return type changes depending on the conditions is... I think this can happen if a function has a bad code shape like when you try to do more than one function or process it.
def get_info(command):
if type == list: #list
result = [1,2,3,4,5]
elif type (command) == int: #integer
result = 3
elif type (command) == str: #String
result = 'string'
else:
# I think it would be better to add a rise here, not just a print.
print('command ({}) is not implemented'.format(command))
return {"Result":result, "TranCd":"get_info"}
Depending on the situation, you can use class
with get_info as a member to bind the return value into a field, or combine the return contents with map
as above to unify it into a single type, or abstract the return value itself into class
. In some cases, there are many ways... 🤔
But the best thing is, I don't think we should make that case...Haha
Have fun programming. Thank you.
It is very difficult for the user to create a function with various return types in a dynamic type language.
Python is definitely a dynamic type of language, but if you look at the api provided, it's consistent.
def get_info(command):
if isinstance(command, (list, tuple, string)): // sequence type
Return [], () "", etc. is of the return //sequence type (implemented__getitem) so the return value can be sliced using []
else: raise error
v = get_info(variable_name)
Because v is consistent with sequence type, you can prevent runtime errors.
Of course, it would be better to return to an immutable tuple than to list.
Personally, I think of it as a case where the sequence type is returned, a single value (int, bowl) of the scalar type is returned when the dict is rerun.
If you provide a sequence to dict function separately, you can only receive a return in sequence form and convert it to sequence to dict function if necessary.
Don't try to do multiple functions in one function.
© 2025 OneMinuteCode. All rights reserved.