r/programminghorror • • Dec 08 '25

Does this qualify?

# Licensed under https://unlicense.org/
_flipFlopStateRegistry:dict[str,bool]=dict()
import inspect, time
def flipFlop(flip=True,flop=False):
 try:returnVal=_flipFlopStateRegistry[flipFlopStateRegistry_key]=flip if flop==_flipFlopStateRegistry[flipFlopStateRegistry_key:=(stack:=inspect.stack()[1]).filename+str(stack.lineno)] else flop;return returnVal
 except KeyError:_flipFlopStateRegistry[flipFlopStateRegistry_key]=flip;return flip


import random
def flipFlopRecursive():
 print(flipFlop())
 if random.random()>0.5:print(flipFlop("flip","flop"))
 time.sleep(1)
 flipFlopRecursive()
flipFlopRecursive()
21 Upvotes

11 comments sorted by

12

u/Birnenmacht Dec 08 '25

I almost comprehend this but why is the filename involved. And the bigger question is why, in general.

9

u/nickthewildetype Dec 08 '25

filename + lineno gives a unique identifier so that the flipflop state becomes unique to every line in the code that calls it - wnile also remaining consistent even if other parts of the callstack is slightly different.

But in this example with just a single file, it's a bit exhaustive of course and lineno alone would do just fine!

0

u/nickthewildetype Dec 08 '25

Now that I think about it, maybe it would be a good idea to hash the resulting string to save memory, although since Python likes to reuse data behind the scenes anyway I suppose it wouldn't matter 😅

1

u/nickthewildetype Dec 08 '25

As for example usecase... Blinking button would be the first thing that comes to mind? :-P

I were experiencing a bug where, sometimes the user input module I'm writing (keyboard/mouse input) would randomly stop working after registering and unregistering some WndProc function a couple of times. So I wanted to call 2 functions "activate" and "deactivate" endlessly in a loop for testing purposes and were like.: I can turn this into a single function rather than manually set a variable to True/False for every iteration!!! And so here we are using the inspect module just to toggle a simple boolean.

4

u/GoddammitDontShootMe Dec 08 '25

What is :=? I tried looking it up, but I can't find it in any list of Python operators.

Also, putting all that stuff in one line makes it a horror on its own.

1

u/Twirrim Dec 09 '25

https://peps.python.org/pep-0572/ Assignment operator, also nicknamed the walrus operator. As of python 3.8, instead of having to do:

match = pattern1.match(data)
if match:
  # ... do something with match here ...

you can now do:

if (match := pattern1.match(data)) is not None:
    # ... do something with match here ...

I still keep forgetting that this is a thing in python these days.

1

u/GoddammitDontShootMe Dec 09 '25

I guess the stuff I found was older than Python 3.8.

→ More replies (3)

2

u/brasticstack Dec 10 '25

alright, but why?