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)
You can trick an interpreter with this ugly oneliner
if None: var = None
It do nothing else but adding a variablevar
to local variable dictionary, not initializing it. Interpreter will throw the UnboundLocalError exception if you try to use this variable in a function afterwards. This would works for very ancient python versions too. Not simple, nor beautiful, but don't expect much from python.Why not just do this:
Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above.
This is nice, because you'll never end up with an uninitialized variable. But be careful -- this doesn't mean that you won't end up with incorrectly initialized variables. If you init something to
None
, make sure that's what you really want, and assign something more meaningful if you can.I usually initialize the variable to something that denotes the type like
or
If it is going to be an object then don't initialize it until you instantiate it:
First of all, my response to the question you've originally asked
Q: How do I discover if a variable is defined at a point in my code?
A: Read up in the source file until you see a line where that variable is defined.
But further, you've given a code example that there are various permutations of that are quite pythonic. You're after a way to scan a sequence for elements that match a condition, so here are some solutions:
Clearly in this example you could replace the
raise
with areturn None
depending on what you wanted to achieve.If you wanted everything that matched the condition you could do this:
There is another way of doing this with
yield
that I won't bother showing you, because it's quite complicated in the way that it works.Further, there is a one line way of achieving this:
I'd heartily recommend that you read Other languages have "variables" (I added it as a related link) – in two minutes you'll know that Python has "names", not "variables".