0

Is it possible to pass types as function aguments as in the below example?

def test(*args):
    '''decorator implementation with asserts'''
    ...


@test(str, int)
def fn1(ma_chaine, mon_entier):
    return ma_chaine * mon_entier

@test(int, int)
def fn2(nb1, nb2):
    return nb1 * nb2

or should I pass them as strings (eg @test('str', 'int)) and inside test function use them with if and elif?

david
  • 1,302
  • 1
  • 10
  • 21

2 Answers2

1

Does it work?

def test(obj, typ):
    if isinstance(obj, typ):
        print('Type Matches')
        return True
    return False

test('mystring', str)

"Type Matches"

Yes.

Should you do this?

Probably not

And some more information of type checking

PyPingu
  • 1,697
  • 1
  • 8
  • 21
  • Thx for your answer. I also inderstand with your link that explicit precondition is far better than this. [code](https://tio.run/##bZBBboQwDEX3OYV3JCM2A5uqUqXeBAUwnVTFQY4zUnt5miCggOrl9/f3s6dveXiq57nHAQSD6Jvlj2BeFaQaPTUSpy@EN8iyWtRs7bHzbAUj68FTJ87TOrM57CI2PTZPZDeccrcaPIOUOTqOSAKO4MdNel@7tK5DuWwIyKJdcBTEUod6yyhBjDn5GSUywYa5gqhL@4KrDq2/W5VS78uTgnCZaMWofOpAdz3apntYR4k54ycSh7ySrzm7BW4Hz57pMvwhs9LU3kugtjrHJDUFJDlNTpwGdN5ftJ4@feSihDo9YGtU@uUfoagLY@b5Fw) – david Jul 23 '19 at 09:26
  • You're effectively trying to make Python into a statically typed language by doing this, which is not very pythonic. If you are using Python 3.6 or higher I would recommend looking at [type hints](https://medium.com/@ageitgey/learn-how-to-use-static-type-checking-in-python-3-6-in-10-minutes-12c86d72677b) which provide some level of static type checking. [Official PEP](https://www.python.org/dev/peps/pep-0484/) – PyPingu Jul 23 '19 at 09:30
0

Python function's argument doesn't care about its type.

You can pass the arguments of any type, and can check the type of arguments.

It is simple you can check the type of arguments what you get.

try

def fn1(ma_chaine, mon_entier):
    if type(ma_chaine) == int && type(mon_entier) == int:
        return ma_chaine * mon_entier
    else:
        raise TypeError("Arguments should be 'int' type. Got '{}' type and '{}' type.".format(type(ma_chaine), type(mon_entier))
nsbb
  • 11
  • 4
  • 1
    As a note it should be made clear that `type() ==` will behave differently from `isinstance()`. Check out the answers [here](https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance). They also handle booleans differently. – PyPingu Jul 23 '19 at 09:11
  • Thanks for the comment! I knew only about 'if ~ is~:' is different as 'if ~ == ~', but I didn't know about isinstance() function. I learn another one from your comment. Thanks again @PyPingu! – nsbb Jul 23 '19 at 10:05