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

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

Related

This question is related to python variable-assignment variable-declaration

The answer is


var_str = str()
var_int = int()

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()

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.


You can trick an interpreter with this ugly oneliner if None: var = None It do nothing else but adding a variable var 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.


It is a good question and unfortunately bad answers as var = None is already assigning a value, and if your script runs multiple times it is overwritten with None every time.

It is not the same as defining without assignment. I am still trying to figure out how to bypass this issue.


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".

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

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

foo = None

which will assign the value None to the variable foo.

EDIT: What you really seem to want to do is just this:

#note how I don't do *anything* with value here
#we can just start using it right inside the loop

for index in sequence:
   if conditionMet:
       value = index
       break

try:
    doSomething(value)
except NameError:
    print "Didn't find anything"

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:

for item in sequence:
    if some_condition(item): 
       found = True
       break
else: # no break or len(sequence) == 0
    found = False

if found:
   do_something(item)

NOTE: if some_condition() raises an exception then found 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:

for item in sequence:
    if some_condition(item):
       do_something(item)
       break

Or

found = False
for item in sequence:
    if some_condition(item):
       found = True
       break

if found:
   do_something(item)

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.

value = None
for index in sequence:
   doSomethingHere
   if conditionMet:
       value = index
       break 

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?"


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)]

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)

Is it possible to declare a variable in Python (var=None):

def decl_var(var=None):
if var is None:
    var = []
var.append(1)
return var

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().


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to variable-assignment

How to assign a value to a TensorFlow variable? Why does foo = filter(...) return a <filter object>, not a list? Creating an array from a text file in Bash Check if returned value is not null and if so assign it, in one line, with one method call Local variable referenced before assignment? Why don't Java's +=, -=, *=, /= compound assignment operators require casting? How do I copy the contents of one ArrayList into another? Python: Assign Value if None Exists Assignment inside lambda expression in Python Expression must be a modifiable L-value

Examples related to variable-declaration

C error: Expected expression before int Declare and assign multiple string variables at the same time Python Variable Declaration When to use extern in C++ Declaring variables inside loops, good practice or bad practice? Is it possible to declare a public variable in vba and assign a default value? Can I simultaneously declare and assign a variable in VBA? How to unset a JavaScript variable? C pointer to array/array of pointers disambiguation Is it possible only to declare a variable without assigning any value in Python?