Last active
July 8, 2019 19:07
-
-
Save himat/0a4639f9ee1e30f54679fa3723359c0e to your computer and use it in GitHub Desktop.
[Mock any python object/function] Create a fake object/function to disable an object/function that is called later #python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Assume our code has some function that is called later (possibly called multiple times). | |
# In the code below, we have a logging function, and we don't want to always use the logger. | |
# Instead of adding an `if disable_logging` line every time we log something with the logging function, | |
# we can instead just replace the logging function with a fake function that does nothing. | |
def mock_logger(*args, **kwargs): | |
pass | |
if disable_logging: | |
logger = mock_logger | |
else: | |
logger = SomeLoggingFunc | |
logger("hi") # Nothing will happen if you use mock_logger |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# We can also replace an entire object with a fake object that does nothing for all object functions. | |
class FakeObject(): | |
def __init__(*args, **kwargs): pass | |
def nop(*args, **kw): pass | |
def __getattr__(self, attr): return self.nop | |
if disable_logging: | |
summary_writer = FakeObject() | |
else: | |
summary_writer = SummaryWriter(logdir=config.summary_dir, comment='Logging Agent') | |
summary_writer.add_scalar(45) # Nothing will happen if using FakeObject |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment