How to have different input types for the same function?

The basic idea of ​​what I want to do:

def aFuncion(string = '', dicti = {}):
    if len(str) > 0:
         print 'you gave string as input'
    if len(dicti) > 0:
         print 'you gave a dict as input'

aFunction(string = 'test')
dict['test'] = test
aFunction(dicti = dict)

I know that such an idea is possible in more OO languages, but is this also possible in python?

I'm doing now

def aFuncion(input):
    if type(input) == str:
         print 'you gave string as input'
    if type(input) == dict:
         print 'you gave a dict as input'

aFunction('test')

But I want the difference to be clear when calling the function

+5
source share
3 answers

This goal of wanting a “distinction to be understood when calling a function” does not fit very well with the language design philosophy. Google "duck print" for more information on this. Accepted input should be clearly spelled out by function docking and that’s all you need to do.

python, , dict, , , , . , , , pop . , , , , .

, , isinstance, , . , .

def aFuncion(input_):
    if isinstance(input_, str):
        print 'you gave a string-like input'
    elif isinstance(input_, dict):
        print 'you gave a dict-like input'

aFunction('test')

python3 hinting. PEP 484.

+3

, , .

, Guido Van Rossum PyPi, .

+6

, . :

def aFunction(str = '', dicti = {}):
    if len(str) > 0:
         print 'you gave string as input'
    if len(dicti) > 0:
         print 'you gave a dict as input'

str = 'test'
dicti = dict([('test', 'test')])
aFunction(str = str)
aFunction(dicti = dicti)
aFunction(str = str, dicti = dicti)
aFunction(dicti = dicti, str = str)

:

you gave string as input
you gave a dict as input
you gave string as input
you gave a dict as input
you gave string as input
you gave a dict as input

, (. , Python?).

0

All Articles