1

For an existing Python project, I need to introduce the "cross cutting" non-functional concern of FLOP counting so I can compute the performance in GFlop per second for that application.

In Scala, I could solve this by having an implicit parameter e.g. flopTracker and have it accessible wherever needed flopTracker.count(N) adding to a total sum. Then at the end of the program do flopTracker.getTotalCount().

In Python I could use a context manager like:

with FlopTracker as flop_tracker:
    # call other modules having flop_tracker accessible ...
    # ...
    logger.info(f"my total flop count is {flop_tracker.get_total_count()}")

What's the Pythonic way to do this? how can I have any module "see" this flop_tracker when available and ideally in a decoupled fashion?

SkyWalker
  • 13,729
  • 18
  • 91
  • 187
  • 1
    Does this answer your question? [Loose late binding v. strict late binding](https://stackoverflow.com/questions/63312608/loose-late-binding-v-strict-late-binding) – MisterMiyagi Feb 22 '21 at 09:56
  • @MisterMiyagi thanks a lot! looks promising :) it looks to me like the `ThreadLocal` scoping in JVMs – SkyWalker Feb 22 '21 at 09:59
  • 2
    Note that depending on what you want to do, ``contextvars`` or just any global object might be more appropriate. The range of ``contextvars`` -> ``threading.local`` -> global is a trade-off between concurrency robustness against overhead. – MisterMiyagi Feb 22 '21 at 10:01
  • 1
    Sounds like you are looking for dependency injection in Python. https://stackoverflow.com/questions/2461702/why-is-ioc-di-not-common-in-python https://python-dependency-injector.ets-labs.org/introduction/di_in_python.html – Kolmar Feb 22 '21 at 14:50

0 Answers0