Does Python have a static variable like C has? I like to avoid a global variable for the usual reasons.

Note: A static variable in a C function will retain its last value.

Recommended Answers

All 3 Replies

As far as I know, Python does not have an official static variable, but you can easily mimic one ...

# a mutable object like a list element as default argument
# will act like a static variable since its address is fixed
def static_num2(list1=[0]):
    list1[0] += 1
    return list1[0]

print static_num2()  # 1
print static_num2()  # 2
print static_num2()  # 3  etc.

This is cool, so initially list1[0] is zero to start the count!
How can you wrap that into a normal bread and butter function?

Well, here would be an example of a "bread and butter" function using the counter ...

def f1(str1, count=[0]):
    # your code
    str1 = str1 + " and butter"
    # the counter
    count[0] += 1
    # return a tuple
    return count[0], str1

print f1("bread")  # (1, 'bread and butter')
print f1("bread")  # (2, 'bread and butter')
print f1("bread")  # (3, 'bread and butter')
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.