Variables, Datatypes, and Objects
Overview
Without incorporating any Ignition-specific objects, it is important to understand the basics of Python. This section seeks to introduce three main Python principles: Variables, Data Types, and Operators. Additionally, this page and the sub-pages herein will provide plenty of examples to get you started.
This section of the manual attempts to introduce these principles so that they may later be used in conjunction with Ignition. The information in this section is far from comprehensive, as Python's official documentation is a better reference for all things Python. However, this page serves as a great way to jump right into the action.
Variables
Variables are created by simply assigning a value to them. Variables do not need to be declared, because Python has a dynamic type system. That means, Python figures out the type of the variable on the fly when the script is executed.
Python Variables
Watch the videoThe following script would print out: 15
x=5
y=3
print x*y
A space may be included on either side of the assignment operator ('='), but is not required. Thus, the following example would be functionality identical as the example above.
x = 5
y = 3
print x * y
Built-in Datatypes
Python features several built-in datatypes. Below is an overview and links to appropriate pages where applicable.
Python Dataypes
Watch the videoWorking with Different Dataypes
Watch the videoNone
There is a special value in Python called None
(with a capital N). This is simply a special value that means no value. This value is equivalent to Java's null
value. None can be used to initialize a variable, but is best when checking to see if something exists before doing extra work:
# If some value is not equal to None...
if something != None:
# ...then do some work
doWork()
Booleans
Python has two built-in values to represent true and false values: True
and False
, respectively (note the capital letters). These can be used when testing for truth, and are implicitly returned when the comparison operator is used:
# Prints True
print 1 == 1
# Prints False
print 1 == 0
When using Booleans, suchs as predicates in an if-statement, you typically don't have to use True or False directly. Instead, many other values are considered True or False. The following values are also considered False:
- None
- Numeric values of 0, such as 0
- Empty Sequences and Dictionaries, like [] or {}
Values aside from the ones mentioned above are considered true, so you can easily utilize the existence of a non-zero value as a True. Note that for integers both positive and negative numbers are True, only a value of 0 is False.
Strings
Literal strings can be typed in using either double quotes or single quotes. This can be handy when your string contains one quote or the other. You can also use the backslash character to escape special characters including these quotes. See the Strings page for more information.
Numeric Types
Numbers can just be typed in normally, like 42 or 3.14159 . Adding a decimal point differentiates an Integer from a Float. More information on Numeric types can be found on the Numeric Types page.
Colors
Working with colors in Python is remarkably easy. You can simply use any tuple of 3 or 4 integers to represent a color in RGB or RGBA. For example, to set a label's text color to red, you can simple do something like this:
label = event.source
label.foreground = (255,0,0) #(red,green,blue)
Additionally, the system.gui.color function allows you to pick a color in a similar fashion:
newColor = system.gui.color(255,0,0)
Lists and Tuples
Python offers a variety of sequence types: most notably Lists and Tuples. These are ordered collections, meaning they are indexed and the sorted order is maintained. More information on these types can be found on the Lists and Tuples page.
newList = [1,2]
newTuple = (2,5,7)
Dictionaries
A Dictionary is a very useful type that holds a set of key-value pairs. Unlike sequences, they are not ordered, so there is no need to sort them. Instead you give each Value in the dictionary a Key, which handles as a reference to Value. You may have used these in other languages and know them as hashmaps, maps, associative memories, or associative arrays. More information on Dictionaries can be found on the Dictionaries page.
newDictionary = {"itemName":5}
JSON
JSON stands for JavaScript Object Notation. While it is not a datatype, it is a way of defining data in a human readable format, and is commonly used in many applications. It comes from the Javascript programming language, but it is language independent. Each JSON object contains lists and objects. A list is a series of ordered values separated by commas that is commonly used within Python. The object works like a dictionary, using any number of name/value pairs, where each value could be any basic datatype, a list, or even another object with its own name/value pairs. Because JSON is just a way of defining data, it can be used in many different programming languages, including Python. This makes it a useful tool for defining data in a way that humans can easily read.
Ignition also has two scripting functions that allow you to convert between a JSON string and a native Python object: system.util.jsonEncode and system.util.jsonDecode.
Official Documentation
For more information on JSON, see http://www.json.org.
Datasets
A Dataset is a multidimensional collection of values, stored in a manner similar to how values on a spreadsheet appear. Python does not natively have a Dataset type. Instead these datasets were created for use inside of Ignition. There are two types of datasets:
- Dataset: Sometimes called a "Standard Dataset", this type is commonly used on many Vision Components, such as the Power Table or Chart, to display multiple values simultaneously.
- PyDataset: Short for "Python Dataset", these datasets act in a manner very similar to a Python Sequence when it comes to accessing specific values, or iteration (see Lists and Tuples). Ignition's built-in system functions that interact with the database typically return a PyDataset. While there are two types of datasets, you can easily convert one type of dataset to the other. Additionally, you can easily create a dataset from a script.
header = ["The Only Column"]
rows = [[1],[2],[3]]
myDataset = system.dataset.toDataSet(header, rows)
Dates
Dates and times can be created in Python with the datetime
and time
libraries. However, the Ignition's built-in system.date functions can also be used instead without having to import either library.
currentTime = system.date.now()
print "The current time is: %s" % currentTime
Using the In-Keyword
Python's in
keyword can be used to check the contents of something for a specific instance of another object. One use is to check the contents of a string for a certain substring:
myString = "Hello World"
subString = "World"
# Here we are using an if-statement to look for the substring. If the substring exists inside of myString, the expression returns True.
if subString in myString:
# This will print out, because the substring "World" exists in the string "Hello World"
print "The word 'World' appears in myString"
The in
keyword can be used to look for a certain object inside of a sequence:
myList = [1,2,3,4]
# If the integer 3 exists in myList, then this will print True, otherwise it will print False.
print 3 in myList
# Check for the Administrator role.
if "Administrator" in system.security.getRoles():
print "Administrator found"
Additionally, the in
keyword can be used in an expression on a while
loop:
myList = [1,2,3,4]
# As long as the integer 4 is in myList, the while loop will continue to iterate.
while 4 in myList:
# pop(0) will remove the first element in the list
myList.pop(0)
else:
print "all done!"
Basic Operators
Python has many common operators as you would expect, or are at least familiar with if you've worked with other scripting languages.
These are just the basics. There are other operators, like bit shift operators and more. Read about them at: http://docs.python.org/library/stdtypes.html
Operator Reference
In regards to Arithmetic Operators, the precision of the returned value depends on the data types of the arguments: including at least one float will return a float, otherwise, an integer is returned.
Operator | Meaning | Example | Output |
---|---|---|---|
+ | Addition. Note that the data type of the returned object depends on the datatype of the arguments being used: |
| 14 14.0 |
- | Subtraction |
| -4 |
* | Multiplication |
| 45 |
/ | Division |
| 2.2222222222222223 |
// | Floored Division: will divide and return just the nearest integer value, even if dividing floats. |
| 2.0 |
% | Modulo: returns just the remainder of the dividend (the left argument) after being divided by the right argument. In the example on the right, the 4.5 divides evenly twice, leaving 1.0 as a remainder. |
| 1.0 |
** | Power: raise the the number on the left to the power of the number on the right. |
| 125 |
Boolean Operators
Operator | Meaning | Example | Output |
---|---|---|---|
or | Returns True if either argument is True. If both are False, then returns False. |
| True |
and | Returns True only if both arguments are True. Otherwise, returns False. |
| False |
not | Returns a boolean value that represents that opposite value of the trailing expression: False becomes True, and True becomes False. |
| False |
Comparison Operators
Operator | Meaning | Example | Output |
---|---|---|---|
< | Less than |
| False False |
<= | Less than or equal to |
| False True |
> | Greater than |
| True False |
>= | Greater than or equal to |
| True True |
== | Equal |
| True False |
!= | Not equal |
| False True |
is | Returns True if both arguments are referring to the same object, otherwise, returns False. |
| False |
is not | Returns True if both arguments are referring to different objects. |
| True |
Order of Operations
Note that there is an order of operations for Arithmetic and Boolean operators that can be modified with parenthesis. For arithmetic they are grouped in tiers and evaluated left-to-right within a given tier:
- Parenthesis
- Exponents
- Multiplication, Division, Modulo
- Addition, Subtraction
6+10*2 # produces 6+(10*2) = 26
6*10+2 # produces (6*10)+2 = 62
10*6%2 # produces (10*6)%2 = 0
10%6*2 # produces (10%6)*2 = 8
For Boolean operators:
- Not
- And
- Or