Python Basics for Plugins
This is a quick introduction to the Python needed for Python-based plugins in Modern CSV. You don't need to be a programmer. Just a few concepts will get you started.
Types
Python has a few basic types of values:
| Type | What it is | Examples |
|---|---|---|
int |
Whole number | 42, -3, 0 |
float |
Decimal number | 3.14, -0.5, 1.0 |
bool |
True or false | True, False |
str |
Text (string) | "Hello", 'Alice', "" |
NoneType |
No value / not set | None |
Python picks the type automatically based on how you write the value. 5 is an int, 5.0 is a float, and "5" or '5' is a string.
Some plugin inputs arrive as strings. Convert them to numbers with int() or float():
count = int("25") # 25
price = float("19.95") # 19.95
label = str(42) # "42"
Variables
A variable stores a value so you can use it later. You create one by giving it a name and assigning a value with =. You do not have to declare its type. Python will figure it out.
price = 50
name = "Alice"
tax_rate = 0.08
is_valid = True
Variable names can contain letters, numbers, and underscores, but must start with a letter or underscore.
Numbers and Arithmetic
Python handles basic math in a straightforward manner.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Add | 3 + 2 |
5 |
- |
Subtract | 10 - 4 |
6 |
* |
Multiply | 5 * 3 |
15 |
/ |
Divide | 7 / 2 |
3.5 |
// |
Floor division | 7 // 2 |
3 |
** |
Power | 2 ** 3 |
8 |
% |
Remainder | 7 % 3 |
1 |
For int and float operands, / returns a float. // rounds down and returns an int when both operands are integers, or a float if either operand is a float (e.g. 7 // 2 is 3, but 7.0 // 2 is 3.0).
You can use parentheses to control the order of operations:
total = (price + shipping) * tax_rate
When updating a variable based on its current value, you can use a shortcut operator:
total += price # same as total = total + price
count -= 1 # same as count = count - 1
value *= 2 # same as value = value * 2
scale /= total # same as scale = scale / total
Use max() or min() to choose the largest or smallest value. They can compare two or more separate values, or they can inspect a list or other collection:
safe_count = max(0, count)
limited_count = min(count, 100)
highest = max(10, 25, 8) # 25
lowest = min([10, 25, 8]) # 8
Strings
Strings are text, written in quotes. Single or double quotes both work.
name = "Alice"
greeting = 'Hello'
Join strings together with +:
message = "Hello, " + name
Repeat a string with *:
divider = "-" * 20
Convert a number to a string with str():
label = "Total: " + str(42)
You can also use f-strings to embed values directly inside a string. Put an f before the opening quote and wrap expressions in {curly braces}:
name = "Alice"
score = 95
message = f"{name} scored {score} points" # "Alice scored 95 points"
total = f"Tax: {price * 0.08:.2f}" # formats to 2 decimal places
Strings also have useful methods:
text = " Total "
clean = text.strip() # "Total"
lower = clean.lower() # "total"
upper = clean.upper() # "TOTAL"
You can chain method calls when each method returns another value:
clean_lower = str(value).strip().lower()
Lists
A list is an ordered collection of values, written with square brackets.
values = [10, 20, 30, 40]
names = ["Alice", "Bob", "Carol"]
Access items by position. Indexes are zero-based, so the first item is index 0:
first = values[0] # 10
second = values[1] # 20
Get the length of a list:
count = len(values) # 4
Add an item to the end with append():
values.append(50) # values is now [10, 20, 30, 40, 50]
Use slices to get part of a list or array:
values = [10, 20, 30, 40]
values[1:] # [20, 30, 40] (from index 1 to the end)
values[:-1] # [10, 20, 30] (everything except the last item)
values[::2] # [10, 30] (every two elements)
values[::-1] # [40, 30, 20, 10] (reversed)
A list can contain other lists, creating a 2D structure (a list of rows):
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
grid[0] # [1, 2, 3] (first row)
grid[0][2] # 3 (first row, third column)
grid[2][1] # 8 (third row, second column)
Dictionaries
A dictionary stores values by name instead of by position. It is written with {curly braces} and uses key: value pairs.
command = {
"id": "filter_above_mean",
"name": "Filter Above Mean",
"description": "Filters rows whose values are above the mean",
}
Access or update a value by using its key in square brackets:
command_id = command["id"] # "filter_above_mean"
command["name"] = "Filter Above Mean"
Dictionary keys are often strings, but the values can be any type, including numbers, lists, or other dictionaries.
A trailing comma after the last item is allowed in multi-line lists, dictionaries, tuples, and function calls. It makes later editing easier.
Tuples and Unpacking
A tuple is an ordered collection like a list, but it is usually used for a small fixed group of values. Tuples are written with parentheses.
cell = (5, 2, "Total")
Unlike a list, a tuple is immutable. That means you cannot add, remove, or replace its items after it is created.
You can unpack a tuple into separate variables:
row, col, value = cell
# row = 5, col = 2, value = "Total"
This also works in loops:
cells = [
(5, 1, "Total"),
(5, 2, 42),
]
for row, col, value in cells:
print(row, col, value)
Comments
Comments are notes in your code that Python ignores. Use # to start a comment -- everything after it on that line is skipped.
# Calculate the total with tax
total = price * 1.08 # 8% tax rate
For longer notes spanning multiple lines, use a pair of """:
"""
This loop goes through each name
and prints a greeting for it
"""
for name in names:
print(f"Hello, {name}")
When a triple-quoted string is the first statement inside a function, it is called a docstring. The formula examples use docstrings to provide the formula name and description:
def add_left_cells():
"""
Name: Add Left Cells
Description: Adds the two cells to the left of the current cell.
"""
return mc.rc(0, -1) + mc.rc(0, -2)
Comparisons
Comparisons produce True or False.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
> |
Greater than | 5 > 3 |
True |
< |
Less than | 5 < 3 |
False |
>= |
Greater than or equal to | 5 >= 5 |
True |
<= |
Less than or equal to | 3 <= 5 |
True |
Combine conditions with and, or, and not:
x > 0 and x < 100 # True if x is between 0 and 100
x == 0 or x == 1 # True if x is 0 or 1
not is_valid # True if is_valid is False
You can also chain comparisons:
0.3 <= probability <= 0.8 # True if probability is between 0.3 and 0.8
Use is None and is not None when checking whether a value has been set:
if total_row is None:
total_row = 0
Use isinstance() to check a value's type:
if isinstance(value, float):
print("This is a decimal number")
if isinstance(value, (int, float)):
print("This is numeric")
If / Else
Use if to run code only when a condition is true. Add elif (else if) for additional conditions and else as a fallback. Remember to include the : character at the end of the if, elif, and else statements.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C or below"
Important: The indented lines under if, elif, and else are the code that runs for that branch. Indentation matters in Python -- use the same number of spaces (typically 4) for each level.
Python also has a compact one-line form for choosing between two values:
result = "large" if count > 100 else "small"
This is the same idea as:
if count > 100:
result = "large"
else:
result = "small"
For Loops
A for loop repeats code for each item in a list or range.
names = ["Alice", "Bob", "Carol"]
for name in names:
print(name)
range(start, end) produces numbers from start up to (but not including) end:
for i in range(1, 6):
print(i) # prints 1, 2, 3, 4, 5
range(start, end, step) lets you count by a specific amount. A negative step counts backward:
for i in range(5, -1, -1):
print(i) # prints 5, 4, 3, 2, 1, 0
Use enumerate() when you need both the position and the value:
values = ["A", "B", "C"]
for offset, value in enumerate(values):
print(offset, value) # 0 A, then 1 B, then 2 C
Use continue to skip to the next loop item, or break to leave the loop early:
for value in values:
if value == "":
continue # skip blank values
if value == "Total":
break # stop when Total is found
print(value)
Generator Expressions
A generator expression produces values one at a time. It looks like a compact for loop and is often placed inside a function call.
values = ["A", "", "C"]
has_blank = any(value == "" for value in values) # True
any() returns True if at least one generated value is true. This is useful for checks such as "does this row have any non-empty cells?"
Functions
A function is a reusable block of code with a name. You define one with def, and it can accept parameters and return a value.
def add(a, b):
return a + b
result = add(3, 5) # 8
Functions can have default parameter values:
def greet(name, greeting="Hello"):
return greeting + ", " + name
greet("Alice") # "Hello, Alice"
greet("Alice", "Welcome") # "Welcome, Alice"
When calling a function, you can pass arguments by position or by keyword. Keyword arguments name the parameter being set, which makes long plugin API calls easier to read:
def resize(width, height):
return width * height
resize(100, 50) # positional arguments
resize(width=100, height=50) # keyword arguments
You can pass a function as a value by using its name without parentheses. This is common when plugin APIs ask for a validator or callback function:
def is_positive(text):
return float(text) > 0
validator = is_positive # passes the function itself
is_valid = is_positive("5") # calls the function now
return sends a value back from a function.
def double(x):
return x * 2
result = double(5) # 10
You can return different values based on conditions:
def describe(value):
if value > 0:
return "positive"
elif value < 0:
return "negative"
else:
return "zero"
A function stops running as soon as it hits a return statement -- any code after it won't execute.
Use return by itself to exit a function early without returning a specific value:
if responses is None:
return
Functions can exist inside other functions:
def calculate_total(prices, tax_rate):
def apply_tax(price):
return price * (1 + tax_rate)
total = 0
for price in prices:
total = total + apply_tax(price)
return total
result = calculate_total([10, 20, 30], 0.08) # 64.8
A nested function can use variables from the outer function. If it needs to update shared state, put the state in a mutable object such as a dictionary:
state = {"minimum": None}
def remember_minimum(text):
state["minimum"] = float(text)
return True
A decorator is a line that starts with @ and is placed immediately before a function. It lets a library mark or modify the function. Some Modern CSV formula examples use @mc.single_run:
@mc.single_run
def fill_total_row():
return
Attributes and Methods
Objects can have values attached to them, called attributes. Access an attribute with a dot:
col = mc.main_selected_cell.col
Objects can also have functions attached to them, called methods. Call a method with a dot and parentheses:
text = " Total "
clean = text.strip()
selected_cells = []
selected_cells.append(mc.Range(0, 0))
Modules use the same dot syntax. For example, np.array() calls the array() function from the np module.
Errors
Use try and except when a line might fail and you want to handle the failure yourself.
text = "12.5"
try:
numeric = float(text)
except Exception:
numeric = 0
Use raise when your code detects a problem and should stop with an error:
if distribution == "unknown":
raise ValueError(f"Unsupported distribution: {distribution}")
Imports
Python code can use functionality from modules (libraries) by importing them. Use import at the top of your code:
import math
math.sqrt(16) # 4.0
math.pi # 3.141592653589793
You can also import specific items or give a module a shorter name:
from math import sqrt, pi
sqrt(16) # 4.0
import numpy as np
np.array([1, 2, 3])
Modern CSV's Python-based plugins come with NumPy and SciPy pre-installed.
Imports can also be inside a function. That can be useful when only one script or formula needs the module.
def run(mc):
import re
text = "A B"
return re.sub(r"\s+", " ", text)
NumPy
NumPy is a library for working with arrays of numbers. It's much faster than plain Python lists for math on large datasets. Many plugin API functions return NumPy arrays.
import numpy as np
a = np.array([1, 2, 3, 4])
a * 2 # array([2, 4, 6, 8])
a + 10 # array([11, 12, 13, 14])
np.sum(a) # 10
np.mean(a) # 2.5
Unlike regular lists, arithmetic on NumPy arrays applies to every element at once without needing a loop.
prices = np.array([10.0, 25.0, 8.50])
with_tax = prices * 1.08 # array([10.8, 27.0, 9.18])
For the full reference, see the NumPy documentation.
SciPy
SciPy builds on NumPy and provides tools for statistics, interpolation, optimization, signal processing, and more.
from scipy import stats
data = [14, 17, 19, 22, 23, 25, 28, 31]
stats.describe(data) # count, mean, variance, min, max, skewness, kurtosis
stats.zscore(data) # z-score of each value
stats.pearsonr(x, y) # correlation between two arrays
For the full reference, see the SciPy documentation.
Additional Resources
- The Python Tutorial - The official beginner guide from Python.org.
- Learn Python in Y Minutes - A single-page crash course through Python syntax.
- W3Schools Python Tutorial - Short lessons with interactive examples you can run in the browser.