Functions Related Tips

Learn how functions play an important role with respect to safety in Python code.

Call that function

A function identifier is a reference to a function, and acts as a claim that the function has been defined and exists somewhere in the interpreter’s memory. When we mention an existing function’s identifier on the command line, the interpreter confirms that the function exists. It also tells us the address of the function in the RAM, but that’s not our concern:

Press + to interact
def add1(x):
return x + 1
print(add1)

The interpreter doesn’t call a function unless we ask it to call the function using the function call operator, also known as the parentheses:

Press + to interact
print(add1(10))

Not calling a function isn’t a syntax or runtime error. There’s nothing wrong with merely referring to the function. In most cases, though, that’s not desirable. This is the correct code:

Press + to interact
def add1(num):
num=num+1
return num
result = add1(10)
print(result)

The code below is potentially correct. It provides an alternative identifier to an existing function:

Press + to interact
increment = add1
result = increment(10)
print(result)

The code below likely incorrect, though:

Press + to interact
result = add1
print(result)

Don’t eval()

The built-in function eval(expr), is the most misused and dangerous function in the Python standard library. The function takes the expr string and evaluates it as a Python expression. Essentially, eval() is a Python interpreter in disguise. We can construct Python expressions on the fly and immediately evaluate them:

Press + to interact
message = 'Hello, world!'
command = 'print(message)'
eval(command)

What could go wrong? Imagine that the command wasn’t produced by our program that is based on a carefully constructed algorithm but was entered by the user. For example, say we develop a program that allows users to calculate arithmetic expressions.

Let’s run the code below for more understanding.

command = input('Enter the expression (only constants, no variables alowed) you would like to calculate: ')
eval(f'print({command})')
Evaluating the arithmetic expression using eval()

Seeing how it works, the user becomes troublesome.

Warning: Don’t attempt to run this code fragment. This function will delete all the files and directories.

os.system('rm -rf /')

The command above will return 0. The zero displayed at the command prompt confirms the worst expectations: the user just removed the content of the root directory. It’s being exaggerated a bit, but the results may be devastating. The problem with eval(expr) is that, in general, it ...