Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function only Once in Python [closed]

Tags:

python

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)
like image 768
Ankush Avatar asked Apr 21 '15 05:04

Ankush


2 Answers

This is how I would to that:

i_run_once_has_been_run = False

def i_run_once(macid):
    global i_run_once_has_been_run

    if i_run_once_has_been_run:
        return

    # do something

    i_run_once_has_been_run = True

@Vaulstein's decorator function would work too, and may even be a bit more pythonic - but it seems like a bit overkill to me.

like image 194
rickcnagy Avatar answered Sep 24 '22 20:09

rickcnagy


Using class,

class CallOnce(object):
    called = False

    def web_service(cls, macid):
        if cls.called:
            print "already called"
            return
        else:
            # do stuff
            print "called once"
            cls.called = True
            return


macid = "123"
call_once_object = CallOnce()
call_once_object.web_service(macid)
call_once_object.web_service(macid)
call_once_object.web_service(macid)

Result is,

I have no name!@sla-334:~/stack_o$ python once.py 
called once
already called
already called
like image 21
pnv Avatar answered Sep 25 '22 20:09

pnv