Is it possible to declare a variable in Python, like so?:
var
so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?
EDIT: I want to do this for cases like this:
value
for index in sequence:
if value == None and conditionMet:
value = index
break
Duplicate
- Uninitialised value in python (by same author)
- Are there any declaration keywords in Python? (by the same author)
If I'm understanding your example right, you don't need to refer to 'value' in the if statement anyway. You're breaking out of the loop as soon as it could be set to anything.
Well, if you want to check if a variable is defined or not then why not check if its in the locals() or globals() arrays? Your code rewritten:
If it's a local variable you are looking for then replace globals() with locals().
You look like you're trying to write C in Python. If you want to find something in a sequence, Python has builtin functions to do that, like
I'm not sure what you're trying to do. Python is a very dynamic language; you don't usually need to declare variables until you're actually going to assign to or use them. I think what you want to do is just
which will assign the value
None
to the variablefoo
.EDIT: What you really seem to want to do is just this:
It's a little difficult to tell if that's really the right style to use from such a short code example, but it is a more "Pythonic" way to work.
EDIT: below is comment by JFS (posted here to show the code)
Unrelated to the OP's question but the above code can be rewritten as:
NOTE: if
some_condition()
raises an exception thenfound
is unbound.NOTE: if len(sequence) == 0 then
item
is unbound.The above code is not advisable. Its purpose is to illustrate how local variables work, namely whether "variable" is "defined" could be determined only at runtime in this case. Preferable way:
Or
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:
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:
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?"
If
None
is a valid data value then you need to the variable another way. You could use:This sentinel is suggested by Nick Coghlan.