DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Advancing Robot Vision and Control
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Using Python Libraries in Java

Trending

  • The Evolution of Scalable and Resilient Container Infrastructure
  • Infrastructure as Code (IaC) Beyond the Basics
  • Driving DevOps With Smart, Scalable Testing
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  1. DZone
  2. Coding
  3. Languages
  4. Python — How to Tell if a Function Has Been Called

Python — How to Tell if a Function Has Been Called

For the Raspberry Pi devs: how to know for sure if a function has been called in your Python code.

By 
Mike Driscoll user avatar
Mike Driscoll
·
Mar. 14, 17 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
23.5K Views

Join the DZone community and get the full member experience.

Join For Free

Last year I ran into a situation where I needed to know if a function had been called. Basically we were trying to prevent shutting down a Twisted event loop twice or starting two of them. Anyway, in my research I stumbled across a fun post on StackOverflow that showed a couple of ways to do this.

The first made use of the fact that everything in Python is an object, including the function itself. Let’s take a look at a simple example:

def self_aware_function(a, b):
    self_aware_function.has_been_called = True
    return a + b

if __name__ == '__main__':
    self_aware_function.has_been_called = False

    for i in range(2):
        if self_aware_function.has_been_called:
            print 'function already called'
        else:
            print 'function not called'

        self_aware_function(1, 2)

In this example, we create an attribute on the function that we named has_been_called. We set it to True when the function is called. When you start your program, you will want to initialize that attribute to False, which we do above. Then we use a for loop to loop twice. The first time through it will check if the function has been called. Since it hasn’t, you will see it fall to the else statement. Now that we called the function, the second time through the loop the first part of the if statement executes.

That StackOverflow post also mentions a neat way to use a decorator to track function calls. Here’s an example I wrote:

import functools


def calltracker(func):
    @functools.wraps(func)
    def wrapper(*args):
        wrapper.has_been_called = True
        return func(*args)
    wrapper.has_been_called = False
    return wrapper

@calltracker
def doubler(number):
    return number * 2

if __name__ == '__main__':
    if not doubler.has_been_called:
        print "You haven't called this function yet"
        doubler(2)

    if doubler.has_been_called:
        print 'doubler has been called!'

In this example, I import functools and create a decorator that I dubbed calltracker. In this function, we set up the same attribute that we did in the previous example, but in this case we attach it to our wrapper (i.e. the decorator). Then we decorate a function and give our code a try. The first if statement checks to see if the function has been called yet. It hasn’t, so we go ahead and call it. Then we confirm that the function was called in our second if statement.

Wrapping Up

While this stuff is certainly useful at runtime, you can also do similar things using Python’s trace module to trace through the execution of your code. This sort of thing is also done via coverage tools. You will also find this kind of functionality in Python Mock objects as a Mock can tell when it has been called.

Anyway, you will hopefully find this exercise as interesting as I did. While I already knew that everything in Python was an object, I hadn’t thought about using that functionality to add attributes to functions.

Python (language)

Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Advancing Robot Vision and Control
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Using Python Libraries in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!