1

Issue understanding the Syntax in on of my project code.

new_addres: str = self.address

vs

new_addres = str(self.address)

new_address is the variable , str is the python keyword , address gets populated at the run time in the code. Could you help me understand why we are using 'str' before assignment operator in the first line? Are both lines of code similar?

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
Pankhuri
  • 11
  • 1

2 Answers2

2

It's a type annotation, indicating which type the variable has.

Python doesn't really care if you use an annotation or not, and certainly won't enforce it: Python isn't a strongly-typed language. But the syntax supports these annotations, because they're really convenient for automatically generating documentation.

In other words,

my_variable:type = expression

is semantically equivalent to

my_variable = expression

as far as Python is concerned. The type annotation is just for other programs to take note of, if they want to.

EDIT: Note that this is a new feature in Python 3.6, so these annotations still aren't common in the real world. Most codebases you see today don't use them.

Draconis
  • 3,209
  • 1
  • 19
  • 31
0

new_addres: str = self.address is type hinting. You can read about how it works in python here. It doesn't make any real difference at runtime, but it's useful in your IDE.

new_addres = str(self.address) is converting self.address to a string.

Vanilla_Brys
  • 63
  • 1
  • 5