Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell when a method is called for first time of many

Tags:

python

methods

I would like to be able to tell when a method has been called for the first time. I primarily need this for when I am printing out to a delimited file, and if it is the first iteration, I would like to print a header before the actual information. This is what I normally do:

def writeFile(number, count):
    if count == 1:
        print('number')
        print(str(count))
    else:
        print(str(count))


count = 1
for i in range(10):
    writeFile(i, count)
    count += 1

This provides the following output:

number
1
2
3
4
5
6
7
8
9
10

Though this achieves the goal I am after, I am curious as to if there is a better/more efficient way of doing this. Is there some way to detect if a method has been called for the first time without having to pass an additional argument to it?

Thank you,

like image 983
Malonge Avatar asked Dec 23 '14 19:12

Malonge


People also ask

How do you check if a method is called in Java?

While you can replace it with blank == true , which will work fine, it's unnecessary to use the == operator at all. Instead, use if (blank) to check if it is true, and if (! blank) to check if it is false.

How do you check if a function has been called in JavaScript?

You can check for a function using the typeof keyword, which will return "function" if given the name of any JavaScript function.

What is main() in Python?

In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.


1 Answers

There are multiple ways to do this. Here are three.

First:

firstRun=True
def writeFile(number):
    global firstRun
    if firstRun:
        print('number')
        firstRun=False
    print(str(number))

for i in range(10):
    writeFile(i)

Second:

def writeFile(number):
    print(str(number))

for i in range(10):
    if not i:
        print('number')
    writeFile(i)

Third:

for i in range(10):
    print(('' if i else 'number\n')+str(i))

I'm assuming this is just a test problem meant to indicate cases where function calls initialize or reset data. I prefer ones that hide the information from the calling function (such as 1). I am new to Python, so I may be using bad practices.

like image 149
dwn Avatar answered Nov 14 '22 23:11

dwn