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
Why not just do this:
var = None
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.
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:
for index in sequence:
if 'value' not in globals() and conditionMet:
value = index
break
If it's a local variable you are looking for then replace globals() with locals().
I usually initialize the variable to something that denotes the type like
var = ""
or
var = 0
If it is going to be an object then don't initialize it until you instantiate it:
var = Var()
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
value = sequence.index(blarg)
If None
is a valid data value then you need to the variable another way. You could use:
var = object()
This sentinel is suggested by Nick Coghlan.
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:
def findFirstMatch(sequence):
for value in sequence:
if matchCondition(value):
return value
raise LookupError("Could not find match in sequence")
Clearly in this example you could replace the raise
with a return None
depending on what you wanted to achieve.
If you wanted everything that matched the condition you could do this:
def findAllMatches(sequence):
matches = []
for value in sequence:
if matchCondition(value):
matches.append(value)
return matches
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:
all_matches = [value for value in sequence if matchCondition(value)]