user2779311
user2779311

Reputation: 1874

Printing the id of the function from within the function in python

How can i find the id of the function from within the function in python

def countmem(a):
    if a==0:
        return
    print("count is ",id(countmem))
    countmem(a-1)


countmem(4)

As every function is called in its own namespace in recursion how can we obtain different id for each function call. This is giving same id for all calls

Upvotes: 1

Views: 318

Answers (1)

tripleee
tripleee

Reputation: 189327

This is really an XY problem. There is really no way for the identical function to not have the identical id between two calls.

Presumably what you really want to know is "how can I distinguish between individual calls to this function". You can do that by taking the id of something which does change between calls, such as the id of the local variable a.

def countmem(a):
    print("countmem with", id(a))
    if a==0:
        return
    print("end of countmem with", id(a))
    return countmem(a-1)

The two prints are not really necessary, but they should illustrate that the id within the same call will not change, which is presumably also important.

Notice that I also added a return statement at the end, though with the current design, the function will always return None anyway. Forgetting to return something from a recursive function is a common beginner problem, so I'm bringing it up tangentially.

Upvotes: 1

Related Questions