Top  | Previous | Next

Scope and Import

The concept of scope is very important in all programming, and Python is no exception. Scope defines what names are directly accessible without any qualifiers. Another way to put this is that the scope determines what variables are defined. When you define a new function, that function gets its own scope. The statements within the function don't operate in the scope of the enclosing code. An example should make this clear:

 

x = 5

print x

def fun():

   x = 3 # this 'x' is not the same as the outer 'x'

   print x

 

fun()

print x

 

This code will print:

5

3

5

 

The assignment x = 3 within the function did not affect the x defined outside the function's scope. Furthermore, if you tried to access x within the function fun without the x = 3 line, you would receive a NameError, because x would not be defined.

 

Global Scope

Besides your immediate scope, there is also the global scope. By declaring a name preceded with the keyword global, your variable will be resolved using the global scope, which is shared by all scripts.

 

global x

# will print whatever value some other script

# assigned to x in the global namespace

print x

 

Using the import keyword

You can import the namespaces defined in other scopes into your scope with the import keyword. Most commonly, you'll import from global library sources, like system (the Ignition standard libraries), app (your project's global script modules), java (importing from the Java standard library), and the various python standard libraries. When you're writing component event handlers, system and app are imported for you automatically. However, if you create a new scope by defining a function, you'll need to import those libraries manually.

 

The import keyword can be used in a variety of forms:

import X
from X import *
from X import Y

 

For example, suppose you wanted to use the java.util.Calendar class for some date manipulations. You could import this in a number of different ways. These examples are equivalent, printing out a date 8 hours before the current date.

 

import java

cal = java.util.Calendar.getInstance()

cal.add(java.util.Calendar.HOUR, -8)

print cal.getTime()

 

from java.util import Calendar

cal = Calendar.getInstance()

cal.add(Calendar.HOUR, -8)

print cal.getTime()