Home > python, Uncategorized > Preserving states across function call in Python

Preserving states across function call in Python

Usually functions in Python is not state preserving. That means functions do not save values between calls. But you can make it happen in the following way

 

# this function remember total from last calls
def summation(value):
    summation.total = getattr(summation,"total",0) + value
    return summation.total 

When execute:

summation(1) == 1 # true

summation(2) == 3 # true

summation(3) == 6 # true

 

Saving states across function call might be useful. For example, here I am trying to accumulate sum over a list of numbers.

# clear last total value

summation.total = 0

[summation(x) for x in [1,2,3]] == [1,3,6] # true

 

Advertisements
Categories: python, Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: