In C++ we have static keyword which in loops is something like this:
for(int x=0; x<10; x++)
{
for(int y=0; y<10; y++)
{
static int number_of_times = 0;
number_of_times++;
}
}
static here makes number_of_times
initialized once. How can I do same thing in python 3.x?
EDIT: Since most of the people got confused I would like to point out that the code I gave is just example of static usage in C++. My real problem is that I want to initialize only ONE time variable in function since I dont want it to be global(blah!) or default parameter..
Best Answer
Assuming what you want is "a variable that is initialised only once on first function call", there's no such thing in Python syntax. But there are ways to get a similar result:
1 - Use a global. Note that in Python, 'global' really means 'global to the module', not 'global to the process':
2 - Wrap you code in a class and use a class attribute (ie: an attribute that is shared by all instances). :
Note that I used a
classmethod
since this code snippet doesn't need anything from an instance3 - Wrap you code in a class, use an instance attribute and provide a shortcut for the method:
4 - Write a callable class and provide a shortcut:
4 bis - use a class attribute and a metaclass
5 - Make a "creative" use of function's default arguments being instantiated only once on module import:
There are still some other possible solutions / hacks, but I think you get the big picture now.
EDIT: given the op's clarifications, ie "Lets say you have a recursive function with default parameter but if someone actually tries to give one more argument to your function it could be catastrophic", it looks like what the OP really wants is something like:
Which, BTW, prove we really had Yet Another XY Problem...