1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Finding imports of a function globally

Discussão em 'Python' iniciado por Stack, Setembro 30, 2024 às 22:32.

  1. Stack

    Stack Membro Participativo

    I am working on a test fixture for the slash framework which needs to modify the behavior of time.sleep. For reasons I cannot use pytest, so I am trying to roll my own basic monkeypatching support.

    I am able to replace time.sleep easily enough for things that just import time, but some things do from time import sleep before my fixture is instantiated. So far I'm using gc.get_referrers to track down any references to sleep before replacing them:

    self._real_sleep = time.sleep
    for ref in gc.get_referrers(time.sleep):
    if (isinstance(ref, dict)
    and "__name__" in ref
    and "sleep" in ref
    and ref["sleep"] is self._real_sleep):
    self._monkey_patch(ref)


    In practice this works, but it feels very ugly. I do have access to reasonably current python (currently on 3.11), just limited ability to add 3rd party dependencies. Is there a better/safer way to find references to a thing or to patch out a thing globally, using only standard library methods?

    Continue reading...

Compartilhe esta Página