python-hooks
python-hooks copied to clipboard
State Inconsistency in Calling Nested Inner Function
trafficstars
🐛 Bug Report
I encountered a discrepancy in the "state" of two nested functions while working on this project. Sometimes "state" does not seem to update its value as expected.
🔄 Steps to Reproduce
The issue can be reproduced using the following code snippet:
def my_stateful_function():
count, set_count = use_state(0)
def increment():
set_count(count+1)
print("count:", count)
return increment
inc = my_stateful_function() # Initial count = 0
inc() # Must Increment: 0 to 1
inc() # Must Increment: 1 to 2
inc() # Must Increment: 2 to 3
my_stateful_function() # Expected: count = 3, Actual: count = 1 gets printed in console
Meanwhile, for comparison, the following method of using states behaves correctly as expected:
def my_stateful_function():
count, set_count = use_state(0)
def increment():
set_count(count+1)
print("count:", count)
return increment
inc1 = my_stateful_function() # count = 0 and prints 0
inc1() # Increment: 0 to 1
inc2 = my_stateful_function() # Print 1
inc2() # Increment: 1 to 2
inc3 = my_stateful_function() # Print 2
inc3() # Increment: 2 to 3
my_stateful_function() # Prints 3
⚙️ Expected behavior
The anticipated outcome is that both code samples should produce identical outputs, maintaining and updating the state correctly across various methods of calling functions.
💻 Environment
- OS: macOS 14.2.1
- Python version: Python 3.11.7
Thanks for the bug report @arvindavoudi, I'm taking a look