7

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,

Malonge
  • 1,980
  • 5
  • 23
  • 33
  • 1
    I think your method is fine - that is, having a second parameter to indicate if it's the first time or not. I would make it a Boolean called something like `firstWrite` and give it a default value of `False`, but it's the same idea. – JKillian Dec 23 '14 at 19:43
  • 1
    You could *not* pass the `count` variable in, and just refer to the global value.... – Chris Pfohl Dec 23 '14 at 19:43
  • 1
    But also look over this answer for another possible way: http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function – JKillian Dec 23 '14 at 19:43
  • Previously answered here: http://stackoverflow.com/questions/1301735/counting-python-method-calls-within-another-method – Tim 333 Dec 23 '14 at 19:45
  • 1
    If you're calling `print(str(count))` anyway, why even have an else statement? – David Reeve Dec 23 '14 at 19:45
  • 3
    if you are writing to or from a file why not write in the function and write the header before you loop – Padraic Cunningham Dec 23 '14 at 19:53

3 Answers3

7

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.

dwn
  • 543
  • 4
  • 15
5

You could write the header to the file before you call the function. That would negate your need for the if statements. I'm a basic level programmer, but this seems logical to me. For example:

def writeFile(count):
    print(str(count))

print('number')
for i in range(10):
    writeFile(i)
raw-bin hood
  • 5,839
  • 6
  • 31
  • 45
3

This is a bit more deep respect to the other answers but I prefer it since it uses the OOP-ness of Python, the idea is to assign to the function itself the "called" variable: this can be done since everything in Python is an object (even a function inside its own scope).

The concept can be extended also to functions defined in other scopes - besides class scope - as well.

class SampleClass:
    def sample(self, *args, **kwargs):
        try:
            if self.__class__.sample.called:
                # do what you have to do with the method 
                print("normal execution")
        except AttributeError:
            # do what you have to do with the first call
            print("first call")
            self.__class__.sample.called = True
            self.__class__.sample(self, *args, **kwargs)

Example:

>>>SampleClass().sample()
first call
normal execution
>>>SampleClass().sample()
normal execution
dteod
  • 195
  • 4