How to define in the parameters the type of arguments that should be sent?

Asked

Viewed 416 times

1

Crude example of what I want (that doesn’t work):

# -*- coding: utf-8 -*-

def a(int(b), str(c)): # Isso não funciona, mas quero algo assim.
    print('Isso é um Numero: %i' %b)
    print('Isso eh uma String: %s' %c)

a(10, 'Texto')



# -*- coding: utf-8 -*-

# Não Quero fazer isso.
def a(b, c):
    # Não Quero fazer isso.
    if not ('int' in str(type(b))): return False
    if not ('str' in str(type(c))): return False

    print('Isso é um Numero: %i' %b)
    print('Isso eh uma String: %s' %c)

a(10, 'Texto')

1 answer

5


Something like that?

def a(b : int, c : str):
    print('Isso é um Numero: %i' %b)
    print('Isso eh uma String: %s' %c)

I put in the Github for future reference.

Possible since Python 3.5 and is improving support, which will culminate in 4.0 being a language with "full" support for variable typing, including parameters, members and elements of structures. It still won’t be a static typing language, think of it as some unit tests automatically inserted for you and that the compiler will get special treatment. There will still be failures, poor performance and other dynamic typing problems, but it is already a considerable gain.

Note that it is not something of normal use, you need to use a library as shown in the documentation. If you want to know more you have the PEP484.

The dynamic typing languages mainstream are going this way one way or another. I’m just not saying that they realized it was a mistake to adopt dynamic typing that doesn’t scale well, because they were right at the time, a language of script You must have that type. The problem is now that these languages have reached an audience, and this audience does not want to give up their preferred language and go to one that better meets their new demands that are not scripts, then language decides to be what it was never to meet these people and continue with success.

  • By type annotation, this should be further promoted!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.