Skip to main content

Writing Functions (Python)

In this document we will create a function that can tell if our input is prime or not. Full code can be found on Github

Cape Function Format

Cape functions are defined as files within a directory. Here's how you can easily start creating a function called isprime:

cape function create isprime

This will create a directory in your current directory called isprime. It will contain an example app.py and requirements.txt file.

Here is the complete code to detect whether our input data was prime (or not):

import math

def isprime(n):
if n < 2:
return False
if n == 2:
return True
for i in range(2, int(math.sqrt(n))):
if n % i == 0:
return False
return True

def cape_handler(arg):
n = int(arg)
result = isprime(n)
if result:
ret = f"{n} is prime"
else:
ret = f"{n} is NOT prime"
return ret

Replace isprime/app.py with the code above. requirements.txt can remain unchanged for this example.

note

The entry point for all Cape functions written in Python is cape_handler. You'll notice we've added a helper function isprime.

Our final project structure should look like:

$ ls isprime
app.py requirements.txt

Function input

Data is passed into the function as binary data. You can pass any kind of data you like via cape run or cape test.

In this example, we cast the binary input data to an int on this line:

n = int(arg)

Full code examples for more sample functions can be found on Github.