Skip to main content
Version: 8.1

Built-In Functions

Python Built-In Functions​

Functions are code that can be called repeatedly from other places. Functions can have parameters passed into them and may return a resulting value. Some functions, like len(), are built-in. Some functions, like system.gui.messageBox(), are part of the scripting libraries provided by Ignition. Some functions, like math.sqrt(), are provided by the Python Standard Library.

Functions are invoked by using their name followed by an argument list surrounded in parentheses. If there are no arguments, you still need an open and close parenthesis.

This section details several useful Built-in Functions, along with some simple examples. See the official docs for more information.

Type Casting Functions​

Python has many functions to convert between data types. Some common type casting functions are listed below.

FunctionNotesExampleOutput
bool()When casting a numeric value to a boolean, a zero value is false, while all non-zero numbers are True.

When casting a String or Unicode value to a boolean, an empty string is False, any other string is True.
# Results in False
print bool("")

# Results in True
print bool("Test")
False
True
int() and long()When casting a float, rounding will not occur automatically to the decimal value. Instead, the round() function should be called.

When casting a String or Unicode value, the string literal needs to be a valid integer or long: decimal values contained in the string will result in a ValueError.

Integers have at least 32 bits of precision, while Longs have unlimited precision.
# Float to Integer
print int(123.8)

# Float to Long
print long(321.8)

# String to Integer
print int("400")

# ValueError: the value is not base 10
print int("400.5")
123
321
400
ValueError
float()When casting a string literal as a float, non-numeric characters in the string will result in an exception, except for a decimal point (".").
# Integer to Float
print float(123)

# String to Float
print float("400.5")
123.0
400.5
str() and unicode()Most objects can be cast as a string representation of some sort, including sequences.
print "First line:" + str(80)

# Even sequences can be cast as a string,
# making for easy concatenation
myList = [1,2,3]
print str(myList)
80
[1, 2, 3]

Checking an Object's Type​

Checking the data type of an object can easily be done with both the type() and isinstance() functions.

FunctionNotesExampleOutput
type(object)When passed a single parameter, this function returns the type of the object.
var = 10
print type(var)
print type(str(var))
type 'int'>
<type 'str'>
isinstance(object, classinfo)Returns True if the object is an instance or subclass of classinfo, otherwise, returns false.

If checking for a string or unicode type, a classinfo of "basestring", which is the base class for both strings and unicode types, would return True.
var = 10
print isinstance(var,int)

strVar = "string"
print isinstance(strVar,basestring)
True
True
Python - Type Validation: type vs isinstance
## type() Example
# This example attempts to validate the type of a variable. As written, this will evaluate as True, and thus the print statement would execute.
var = "My String"
if type(var) == type(""):
print "Variable 'var' is a string"

## isinstance() Example
# The isinstance() function can offer the same functionality as above.
var = "My String"
if isinstance(var, str): # Note the lack of quotation marks around the classinfo parameter. We want to reference the class str, not the string "str".
print "Variable 'var' is a string"

Generating a Range of Values​

In some cases, it is useful to generate a range of integers for iteration. Python's range() function will return a list of integers.

FunctionNotesExampleOutput
range([start,] stop[, step])Returns a list of progressively greater integers.

start - Integer value denoting the initial value in the list. If omitted, defaults to 0. This parameter is inclusive.

stop - Integer value, determines when to cease generating integers. This parameter is exclusive.

step - Integer value to increment each new integer by. If omitted, step defaults to 1.

If step is positive, integers will be generated as long as ( start + i * step < stop) is true.
If step is negative, integers will be generated as long as ( start + i * step > stop) is true.
print range(5)
print range(1, 5)
print range(1, 10, 3)
print range(15, 0, -3)
[0, 1, 2, 3, 4]
[1, 2, 3, 4]
[1, 4, 7]
[15, 12, 9, 6, 3]

Assume we need to read from five separate Tags with a nearly identical Tag path in a single script:

Pseudocode - Tag Path
[Provider]Folder/Sub_Folder_1/Tag
[Provider]Folder/Sub_Folder_2/Tag
[Provider]Folder/Sub_Folder_3/Tag
[Provider]Folder/Sub_Folder_4/Tag
[Provider]Folder/Sub_Folder_5/Tag

Instead of manually typing each path, we could use range() in a for loop that would write the paths automatically.

Python - Range in a For Loop
# Initialize an empty list that will ultimately hold all the Tag paths.
tagPaths = []

# Use range to repeatedly append 5 tag paths to the tagPaths list: starting with a value of 1, and ending with a value of 5.
for num in range(1,6):
# Use String Formatting to create a Tag path with the iterator's (num) value.
tagPaths.append("[Provider]Folder/Sub_Folder_%i/Tag" % num)

# Now that tagPaths contains all our tag paths, we can use the list to interact with the tag, such as by reading their values simultaneously.
tagValues = system.tag.readAll(tagPaths).value

Rounding Numbers​

You can round numbers inside Python with a few simple functions.

FunctionNotesExampleOutput
round(number[, digits])When passed a single parameter, this function returns a rounded integer value of a number. If the decimal is greater than or equal to .5, the it rounds up, less than .5 rounds down.

If the optional digits argument is used, then it rounds to that many decimal places.
var = 10.236981
print round(var)
print round(var,3)
10
10.237
math.floor(number)Returns a truncated integer from the number given. The largest integer value less than or equal to number.

Note that the example needs to import that math library before being able to call floor().
import math

var = 100.938
print math.floor(var)
100.0
math.ceil(number)Returns the ceiling integer from the number given. The smallest integer value greater than or equal to number.

Note that the example needs to import that math library before being able to call ceil().
import math

var = 100.138
print math.ceil(var)
101.0
Python - Simple Casting
stringVar = "40"

# Without using int(), this line would cause an exception. However int() is able to cast the type of stringVar's value to an integer.
print 20 + int(stringVar)

# Type casting is also useful in cases where a string parameter is required, but a numerical value should be given,
# such as the message parameter in system.gui.messageBox().
intVar = 60
# Note that this could also be accomplished with String Formatting instead of using str().
system.gui.messageBox(str(intVar))