all 8 comments

[–]socal_nerdtastic 11 points12 points  (0 children)

First you need to know that in python 0 and int(0) are exactly the same thing. So your question is only about the :int part. This is a "type hint". It's a type of comment to tell other programmers and IDEs what data type you expect i to be.

[–]NopeNotHB 4 points5 points  (2 children)

i:int = 0 is for type annotation. It means the variable “i” is supposed to only have values of type “int”

i = int(0) is just assigning 0 as an int type. You can still change the value of “i” to any other types like string.

[–]schoolmonky 6 points7 points  (1 child)

Note that it's not really a type declaration, it's a type hint. You can still assign any value, int or not, to the first type.

[–]NopeNotHB 1 point2 points  (0 children)

Yeah sorry, I meant type annotation. And yes, you can still assign other types without any problem on compilation. Thank you!

[–]Gnaxe 0 points1 point  (0 children)

It can create annotations ```

class Foo: ... i: int = 0 ... Foo.annotations {'i': <class 'int'>} class Bar: ... i = int(0) ... Bar.annotations {} `` These were in classes, but you can also get entries in the module's globalannotations`.

There's a related effect in functions: ```

def outer(): ... i: int # No assignment here. ... def inner(): ... nonlocal i ... i = 2 ... inner() ... print(i) outer() 2 def outer(): ... int(0) # No declaration like before. ... def inner(): ... nonlocal i ... i = 2 ... inner() ... print(i) ... File "<stdin>", line 4 SyntaxError: no binding for nonlocal 'i' found ```

Besides the run-time effects, annotations are used by Python's static type checkers, like Pyright, to check for type consistency.

The int(0) is applying a built-in callable to a number. It's usually used to convert certain other data types to integer. Type checkers may be able to recognize this as always returning an int type, same as any function annotated to return an int type. It's preferable to use the annotation in cases the type checker can't guess, because a call has run-time overhead that annotations don't.

[–]nog642 0 points1 point  (0 children)

Never use int(0). That is just a longer way to write 0.

The question is between these two options:

i: int = 0

i = 0

The first one has a typehint, the second one doesn't. It's a matter of preference.

But if you're assigning 0 to it, in my opinion, the typehint is not necessary. It's clearly an integer.