0

print(type((lambda x, y, z: int((x + y + z)/3))(10, 11, 12)))

In the above code, I have used int() annotation but as per the python documentation, lambda functions cannot contain annotations. Then why am I not getting any error when using an annotation?

Steve
  • 15
  • 6
  • 2
    I see no type annotations here. – quamrana Sep 01 '23 at 13:03
  • Isn't int an annotation? I even asked ChatGPT before posting question. It said it is an annotation – Steve Sep 01 '23 at 13:04
  • The `int` in your lambda is part of the expression it evaluates when called: It computes something with x,y and z and passes the result to `int()` to return an integer result at the end. – quamrana Sep 01 '23 at 13:06
  • Do the answers to this [question](https://stackoverflow.com/questions/33833881/is-it-possible-to-type-hint-a-lambda-function) help at all? – quamrana Sep 01 '23 at 13:07
  • @quamrana No, it's not related – Steve Sep 01 '23 at 13:14
  • How do you know that? – quamrana Sep 01 '23 at 13:16
  • The answers are based on PEP 256 and I check it but there is nothing about lambda functions – Steve Sep 01 '23 at 13:18
  • 1
    In your code you are not using `int` as a type annotation. You're using to to create an [`int`](https://docs.python.org/3/library/functions.html#int)-type object initialised with a value supplied within the brackets. – Matt Pitkin Sep 01 '23 at 13:20
  • The answers say that you can't directly type hint the parameters of a lambda, but what you can do is to create a variable, that is set equal to your lambda, which itself contains the annotations that you are after. – quamrana Sep 01 '23 at 13:22
  • 1
    ChatGPT is unreliable as a fact checking tool to say the least, and it can be wildly inconsistent. The `int` keyword CAN be used to type annotate but it is NOT used as a type annotation here, it is used as a function to cast the parameter to the `int` type. – rochard4u Sep 01 '23 at 13:29
  • @rochard4u Got it, thanks for explaining. I have one question though, you said that `int` can be used to annotate but it cannot be used in a `lambda function`, right? – Steve Sep 01 '23 at 13:49
  • Python's built-in function `int()` can be used as a function, as a type hint: `int` on variables, parameters and return types, but not on the parameters of lambdas, due to syntactical limitations. – quamrana Sep 01 '23 at 14:13
  • From https://docs.python.org/3/library/stdtypes.html The constructors int(), float(), and complex() can be used to produce numbers of a specific type. – Kenny Ostrom Sep 01 '23 at 14:29

0 Answers0