How to call a function only Once in Python
Question: here I want to call web service function only once throughout the program. how
to accomplish this anybody suggest me

    
    
    import sys,os
    
    def web_service(macid):
            # do something
    
    if "__name__" = "__main__" :
          web_service(macid)
    


Answer: You can use a decorator.

    
    
    def run_once(f):
        def wrapper(*args, **kwargs):
            if not wrapper.has_run:
                 wrapper.has_run = True
                 return f(*args, **kwargs)
        wrapper.has_run = False
        return wrapper
    
    @run_once
    def web_service(macid):
        return doSomething
    

Now `web_service` will only run once. Other calls to it will return `None`.
Just add an `else` clause to the `if` if you want it to return something else.
From your example, it doesn't need to return anything, ever.

If you don't control the creation of the function, or the function needs to be
used normally in other contexts, you can just apply the decorator manually as
well:

    
    
    action = run_once(web_service)
    while True:
        if predicate:
            action()
    

This will leave `web_service` available for other uses.

Finally, if you need to only run it once twice, then you can just do this:

    
    
    action = run_once(web_service)
    action() # run once the first time
    
    action.has_run = False
    action() # run once the second time
    

