3

For example, the following, the first parameter should be restricted to a string, and the second parameter should be a function. However, this is wrong syntax for both. Anyone can help suggest the correct syntax to impose the type restriction?

def GetArg(msg:String, converter:lambda, default):
    print("{}, the default is '{}':".format(msg, default))
    return converter(stdin.readline().strip())

It gives error

Traceback (most recent call last):
  File "E:/stdin_ext.py", line 4, in <module>
    def GetArg(msg:String, converter, default:String):
NameError: name 'String' is not defined

and

  File "E:/stdin_ext.py", line 4
    def GetArg(msg:String, converter:lambda, default:String):
                                       ^
SyntaxError: invalid syntax

2 Answers 2

2

You can use the typing module.

from typing import Callable

def get_arg(msg: str, converter: Callable[[str], str], default) -> str:
    print(f"{msg}, the default is '{default}':")
    return converter(stdin.readline().strip())

assuming your function converter takes a string a returns a string, and that get_arg returns a string. Note the code has also been modified to follow python's naming convention and uses f strings over older style format strings.

Also note that these type hints are just that, hints. They are not checked statically or at runtime. Although, certain IDE's will help you ensure they are correct.

Sign up to request clarification or add additional context in comments.

Comments

0

You should use str instead of String and Callable instead of lambda:

from typing import Callable    

def GetArg(msg:str, converter:Callable, default):
    print("{}, the default is '{}':".format(msg, default))
    return converter(stdin.readline().strip())

That is, unless you have a specific class called String and you are expecting an argument of its type.

When you write lambda you are defining a new lambda, not specifying a type for a function, whence the error.

I believe it is also important to point out that types in python are only a useful notation but it does not raise any error by itself, for example I could still call GetArg(1,2,3) and don't get any error just by the type hinting (of course I would get an error trying to pass an argument to an int afterwards).

2 Comments

Isn't a Callable annotation, e.g. get_next_item: Callable[[], str] a better fit?
Callable[[], str] implies that the function takes no arguments and returns a string. This is not the case, as the function clearly takes a string. @RachSharp was just giving an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.