14534

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 it clear, but say val is already there, but nothing is assigned to it.

Duplicate: Just declaring a variable in Python?

Answer1:

Will throw a NameError exception:

>>> val Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'val' is not defined

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

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

or

if 'val' in dir(): print('val set') else: print('val not set')

Answer2:

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 is None: print "val is None"

Answer3:

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.

Answer4:

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

Answer5:

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?

<strong>EDIT:</strong> 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

Answer6:

try: print val except NameError: print "val wasn't set."

Answer7:

To add to phihag's answer: you can use dir() to get a list of all of the variables in the current scope, so if you want to test if var is in the current scope without using exceptions, you can do:

if 'var' in dir(): # var is in scope

Answer8:

<strong>Q: How do I discover if a variable is defined at a point in my code?</strong>

<strong>A: Read up in the source file until you see a line where that variable is defined.</strong>

Answer9:

Usually a value of None is used to mark something as "declared but not yet initialized; I would consider an uninitialized variable a defekt in the code

Recommend

  • Sql indexes vs full table scan
  • Class implementation in a header file == bad style? [duplicate]
  • Get all existing pointers to an object
  • Changing Jupyter Notebook start up folder by modifying “start in” not working any more
  • extjs4 catching the scroll event on panel
  • C++ Single function pointer for all template instances
  • import scipy.sparse failed
  • How to copy styled text in JTextPane
  • Access user's phone number on iOS 7
  • Why does it draw lines in the wrong place?
  • SonarQube: Cannot deactivate rule with missing quality profile
  • Updating both a ConcurrentHashMap and an AtomicInteger safely
  • During installation of Django, why do I keep getting ImportError: No module named django?
  • where do I find the xml.dom python package for the python-2.6.0-8.9.28 and I have a suse/x86_64 vers
  • Python pickle not one-to-one: different pickles give same object
  • How to add a focus style to an editable ComboBox in WPF
  • List images(01.png) and descriptions(01.txt) from directory
  • Diff between two dataframes in pandas
  • Copy to all folders batch file?
  • Date Conversion from yyyy-mm-dd to dd-mm-yyyy
  • Debug.DrawLine not showing in the GameView
  • Xcode 4 NSLog Macro link in Xcode 3
  • Converting a WriteableBitmap image ToArray in UWP
  • How to test if a URL from an Eclipse bundle is a directory?
  • Refering to the class itself from within a class mehod in Objective C
  • Reading JSON from a file using C++ REST SDK (Casablanca)
  • Why value captured by reference in lambda is broken? [duplicate]
  • CSS Linear-gradient formatting issue accross different browsers
  • How to extract text from Word files using C#?
  • javascript inside java/jsp code
  • AT Commands to Send SMS not working in Windows 8.1
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • How do I configure my settings file to work with unit tests?
  • File not found error Google Drive API
  • Qt: Run a script BEFORE make
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Is it possible to post an object from jquery to bottle.py?
  • Does armcc optimizes non-volatile variables with -O0?
  • Conditional In-Line CSS for IE and Others?
  • Python/Django TangoWithDjango Models and Databases