A bit reversed, but this should work:
def foo(): foo.counter += 1 print "Counter is %d" % foo.counter foo.counter = 0
If you want the counter initialization code at the top instead of the bottom, you can create a decorator:
def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate
Then use the code like this:
@static_vars(counter=0) def foo(): foo.counter += 1 print "Counter is %d" % foo.counter
It’ll still require you to use the foo.
prefix, unfortunately.
(Credit: @ony)
Related Posts:
- Creating a static class with no instances
- Are static class variables possible in Python?
- How do I copy a file in Python?
- Pig Latin Translator
- Understanding slice notation
- How do you round UP a number?
- How to open a file using the open with statement
- How to comment out a block of code in Python [duplicate]
- Using “with open() as file” method, how to write more than once? [duplicate]
- How do I get a substring of a string in Python?
- strip(char) on a string
- How can I represent an infinite number in Python?
- Constructing pandas DataFrame from values in variables gives “ValueError: If using all scalar values, you must pass an index”
- TypeError: ‘NoneType’ object is not iterable in Python
- Relative imports – ModuleNotFoundError: No module named x
- ValueError: invalid literal for int() with base 10: ”
- What does the “yield” keyword do?
- How do I get the number of elements in a list?
- if/else in a list comprehension
- data type not understood
- How to read a text file into a string variable and strip newlines?
- What does hash do in python?
- How to copy a dictionary and only edit the copy
- How to avoid “RuntimeError: dictionary changed size during iteration” error?
- if/else in a list comprehension
- Could not find a version that satisfies the requirement tensorflow
- Creating an empty Pandas DataFrame, then filling it?
- Finding the average of a list
- How to solve dictionary changed size during iteration error?
- iloc giving ‘IndexError: single positional indexer is out-of-bounds’
- What does “\r” do in the following script?
- Anaconda vs. miniconda
- No module named serial
- ImportError: No module named psycopg2
- DataFrame constructor not properly called
- How does functools partial do what it does?
- How to customize a scatter matrix to see all titles?
- What is the problem with shadowing names defined in outer scopes?
- TypeError: write() argument must be str, not bytes (Python 3 vs Python 2 )
- How to clear the interpreter console?
- How to make a class JSON serializable
- What does the ‘b’ character do in front of a string literal?
- How can I upgrade NumPy?
- How to get element-wise matrix multiplication (Hadamard product) in numpy?
- Matplotlib automatic legend outside plot
- Why am I getting this syntax error: keyword can’t be an expression
- Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
- What is dtype(‘O’), in pandas?
- ctypes – Beginner
- Keras, how do I predict after I trained a model?
- How do I find out my PYTHONPATH using Python?
- Flask ImportError: No Module Named Flask
- ModuleNotFoundError: No module named ‘MySQLdb’
- How to change dataframe column names in pyspark?
- Normalize data in pandas
- Can’t broadcast input array from shape (3,1) into shape (3,)
- How to create an array of bits in Python?
- Setting Django up to use MySQL
- In Python, when to use a Dictionary, List or Set?
- How can I check for NaN values?
- How to troubleshoot an “AttributeError: __exit__” in multiproccesing in Python?
- TypeError : Unhashable type
- Read PDF in Python and convert to text in PDF
- Importing variables from another file in Python
- How to read a file without newlines?
- Encrypt & Decrypt using PyCrypto AES 256
- Is there a list of Pytz Timezones?
- Flask example with POST
- Error: Segmentation fault (core dumped)
- can’t open tensorboard 0.0.0.0:6006 or localhost:6006
- ImportError: No module named six
- Easy pretty printing of floats?
- Algorithm for solving Sudoku
- How to read pickle file?
- Logical indexing with lists
- How to set timeout on python’s socket recv method?
- How does str(list) work?
- Automatic indentation for Python in Notepad++
- pandas groupby sort within groups
- Python Socket Receive Large Amount of Data
- Is there a head and tail method for Numpy array?
- What should I use to open a url instead of urlopen in urllib3
- How to find out whether a file is at its `eof`?
- TypeError: Image data can not convert to float
- coercing to Unicode: need string or buffer, NoneType found when rendering in django admin
- Convert from ASCII string encoded in Hex to plain ASCII?
- Simple way to create matrix of random numbers
- pandas: multiple conditions while indexing data frame – unexpected behavior
- What is related_name used for?
- Symbol not found: __PyCodecInfo_GetIncrementalDecoder
- How can I tail a log file in Python?
- How to write unicode strings into a file?
- python-How to set global variables in Flask?
- How do I install pip on macOS or OS X?
- NameError: name ‘get_ipython’ is not defined
- Equivalent to matlab’s imagesc in matplotlib? [duplicate]
- bash: syntax error near unexpected token `(‘ – Python
- Find all files in a directory with extension .txt in Python
- “public” or “private” attribute in Python ? What is the best way?
- Running a python script within wordpress