Understanding How Python Passes Functions Without Parentheses
This article explains why assigning a function to a variable without parentheses doesn’t invoke it, how to pass functions as arguments in Python, and demonstrates the concept with a Prisoner’s Dilemma code example, clarifying common misconceptions about function calls and references.
1. Introduction
In a Python discussion group a user asked why the following code does not pass arguments to the functions tit_for_tat and rat:
strategy_1 = tit_for_tat
strategy_2 = rat
# later
total_sentence_a, total_sentence_b = calculate_sentence(rounds, strategy_1, strategy_2)The confusion stems from treating the assignment as a function call.
2. Explanation
Writing strategy_1 = tit_for_tat merely creates a reference to the function; it does not execute it because there are no parentheses. The same applies to strategy_2 = rat. When the function calculate_sentence receives these references, it can invoke them later with action_a = strategy_a(history) and action_b = strategy_b(history).
Printing the variable shows a function object, e.g.:
strategy_1 = tit_for_tat
print(strategy_1) # <function tit_for_tat at 0x...>Only when parentheses are added does the function execute:
print(strategy_1()) # runs tit_for_tat and prints its return valueAn illustrative screenshot (shown below) highlights the two code blocks: the green box where the functions are defined and the yellow box where they are called with parentheses.
Another screenshot demonstrates the same idea after removing the unnecessary variable assignments and calling the functions directly inside calculate_sentence.
3. Conclusion
The key takeaway is that a function name without parentheses is a reference that can be passed around and invoked later. Assigning the reference to another variable is optional; you can pass the original function directly to another function’s parameters.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
