If you are short on time skip to the bottom. The example I provided is not guaranteed as I do not have enough information from you.
To clarify I am answering the underlying question, "how can I selectively decorate a function". I don't have your underlying code or a definition of the decorator function to work with.
EDIT An "avoid repeating yourself" concern was raised about the main function. You can conditionally include modules through the same mechanism in python. Just add your main routine to two different files and include the routine you want to use. I have demonstrated how to do this at the bottom.
There are many ways to skin this cat, this is just the method I prefer since everything stays nice and encapsulated. The underlying principle is the same though : you can include decorators and other symbols that don't exist without generating "compile time" errors in python provided the section including them is "dead code". Python is a lot more lenient than other languages are where this is concerned.
I will include an example that might work at the bottom, but again, I don't have your underlying code.
First the principle.
To selectively decorate a function, you can just decorate a method
def external_func(func):
def dostuff():
print("hi there!")
return dostuff
class selectively_decorate :
def __init__(self):
global dodecorate
if dodecorate:
"""
Try replacing this with @doesntexist
if dodecorate is falsy you can still create an instance
"""
@external_func
def doTheThing():
return 1
else:
def doTheThing():
print("well hello yourself!")
return 1
doTheThing()
Example
dodecorate=0
a=selectively_decorate()
Outputs
well hello yourself!
Example
dodecorate=1
a=selectively_decorate()
Outputs
hi there!
In your case this might work :
# load the Rasp Pi tkgpio simulator
from tkgpio import TkCircuit
is_simulation = 0
class config_loader:
def __init__(self, jsonFile):
global is_simulation
# get simulator configuration settings
with open(jsonFile, "r") as file:
self.configuration = load(file)
self.circuit = TkCircuit(self.configuration)
""""
You do not need to repeat the decorator or definition of main
It is included here only to show that it can be selectively
included
"""
if is_simulation :
from module1 import main_routine
"""
In other words, you can delete the next three lines...
"""
@circuit.run
def main() :
main_routine()
else :
from module2 import main.routine
"""
... and decrease the indent for the next three one level
"""
@circuit.run
def main() :
main_routine()
main()
load = config_loader("EMSSimV8.json")
Obviously this example can be simplified further, but hopefully the idea has been adequately demonstrated.