Skip to content Skip to sidebar Skip to footer

Uninitialized Value In Python?

What's the uninitialized value in Python, so I can compare if something is initialized, like: val if val == undefined ? EDIT: added a pseudo keyword. EDIT2: I think I didn't make

Solution 1:

Will throw a NameError exception:

>>> val
Traceback (most recent calllast):
  File "<stdin>", line 1, in<module>
NameError: name 'val'isnot defined

You can either catch that or use 'val' in dir(), i.e.:

try:
    val
except NameError:
    print("val not set")

or

if'val'indir():
    print('val set')
else:
    print('val not set')

Solution 2:

In python, variables either refer to an object, or they don't exist. If they don't exist, you will get a NameError. Of course, one of the objects they might refer to is None.

try:
   val
except NameError:
   print"val is not set"if val isNone:
   print"val is None"

Solution 3:

A name does not exist unless a value is assigned to it. There is None, which generally represents no usable value, but it is a value in its own right.

Solution 4:

This question leads on to some fun diversions concerning the nature of python objects and it's garbage collector:

It's probably helpful to understand that all variables in python are really pointers, that is they are names in a namespace (implemented as a hash-table) whch point to an address in memory where the object actually resides.

Asking for the value of an uninitialized variable is the same as asking for the value of the thing a pointer points to when the pointer has not yet been created yet... it's obviously nonsense which is why the most sensible thing Python can do is throw a meaningful NameError.

Another oddity of the python language is that it's possible that an object exists long before you execute an assignment statement. Consider:

a = 1

Did you magically create an int(1) object here? Nope - it already existed. Since int(1) is an immutable singleton there are already a few hundred pointers to it:

>>>sys.getrefcount(a)
592
>>>

Fun, eh?

EDIT: commment by JFS (posted here to show the code)

>>>a = 1 + 1>>>sys.getrefcount(a) # integers less than 256 (or so) are cached
145
>>>b = 1000 + 1000>>>sys.getrefcount(b) 
2
>>>sys.getrefcount(2000)
3
>>>sys.getrefcount(1000+1000)
2

Solution 5:

In Python, for a variable to exist, something must have been assigned to it. You can think of your variable name as a dictionary key that must have some value associated with it (even if that value is None).

Post a Comment for "Uninitialized Value In Python?"