0

I'm newbie in python.

Is there analogue of static keyword in python? I needed to implement a simple function allocating an integer ID from the pool, in fact it just increments a global variable and returns it:

id = -1

def generate_id():
    global id
    id += 1
    return id

Is this the right way to do it? In C I could declare a static variable in the function.

Mark
  • 6,052
  • 8
  • 61
  • 129
  • 1
    Does this answer your question? [What is the Python equivalent of static variables inside a function?](https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function) – FObersteiner Dec 02 '19 at 15:15
  • @MrFuppes, thanks, I will read that thread. – Mark Dec 02 '19 at 15:47

2 Answers2

1

In python there is no such thing as "static" keyword unlike java.

For Funtions

You can add attributes to a function, and use it as a static variable.

def incrfunc():
  incrfunc.tab += 1
  print incrfunc.tab

# initialize
incrfunc.tab = 0

For Class

However, if you are making use of the classes in python below is the language convention.

All variables which are assigned a value in class declaration are class variables. And variables which are assigned values inside class methods are instance variables.

class CSStudent: 
    stream = 'cse'                  # Class Variable 
    def __init__(self,name,roll): 
        self.name = name            # Instance Variable 
        self.roll = roll            # Instance Variable 

NOTE: If you ask me, it would always be good to make use of classes and use them inside off a class, it is my opinion.

forkdbloke
  • 1,505
  • 2
  • 12
  • 29
1

The simple way would be to return a "generator" function that forms a closure over a local, then just manipulate the local:

def new_id_generator():
    id = 0

    def gen():
        nonlocal id
        id += 1
        return id

    return gen

g = new_id_generator()

print(g(), g()) # 1 2
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • thanks for feedback. In new_id_generator() function -- is it guaranteed that `id` variable is only visible inside of `new_id_generator()` ? So in other words, any other code in the script won't be able to touch/change `id` ? – Mark Dec 02 '19 at 15:47
  • @Mark There's potentially some bizarre hack by inspecting stack frames that will allow it to be changed, but it will be much harder than it would by having it as a attribute of a function or your own class. Python doesn't have strict "private" controls, so you can really only discourage certain behavior, not outright prevent it. I think this is about as "private" as you'll be able to get. – Carcigenicate Dec 02 '19 at 16:00