Is it possible only to declare a variable without assigning any value in Python?

Is it possible only to declare a variable without assigning any value in Python?

Why not just do this:

var = None

Python is dynamic, so you dont need to declare things; they exist automatically in the first scope where theyre assigned. So, all you need is a regular old assignment statement as above.

This is nice, because youll never end up with an uninitialized variable. But be careful — this doesnt mean that you wont end up with incorrectly initialized variables. If you init something to None, make sure thats what you really want, and assign something more meaningful if you can.

In Python 3.6+ you could use Variable Annotations for this:

https://www.python.org/dev/peps/pep-0526/#abstract

PEP 484 introduced type hints, a.k.a. type annotations. While its main focus was function annotations, it also introduced the notion of type comments to annotate variables:

# captain is a string (Note: initial value is a problem)
captain = ...  # type: str

PEP 526 aims at adding syntax to Python for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments:

captain: str  # Note: no initial value!

It seems to be more directly in line with what you were asking Is it possible only to declare a variable without assigning any value in Python?

Is it possible only to declare a variable without assigning any value in Python?

Id heartily recommend that you read Other languages have variables (I added it as a related link) – in two minutes youll know that Python has names, not variables.

val = None
# ...
if val is None:
   val = any_object

Leave a Reply

Your email address will not be published.