0

How can I stop importing the current module?

For example, let's say I have this code:

try:
    import RPi.GPIO as GPIO
except ImportError:
    # not on a raspberry pi, warning functions do nothing
    warn_with_led = lambda: None
    warn_with_sound = lambda: None
else:
    # on a raspberry pi
    def warn_with_led():
        GPIO.setmode(GPIO.BCM)
        # more stuff
        # more stuff
        # more stuff
        GPIO.cleanup()

    def warn_with_sound():
        GPIO.setmode(GPIO.BCM)
        # more stuff
        # more stuff
        # more stuff
        GPIO.cleanup()

Instead of writing the whole code with the extra indentation level (created by the import try/except), is there a way to exit/return from the current file? Is there a solution removing the indentation, maybe like:

try:
    import RPi.GPIO as GPIO
except ImportError:
    # not on a raspberry pi, warning functions do nothing
    warn_with_led = lambda: None
    warn_with_sound = lambda: None
    exit_this_module()   # <========= I would like to exit this file only

def warn_with_led():
    GPIO.setmode(GPIO.BCM)
    # more stuff
    # more stuff
    # more stuff
    GPIO.cleanup()

def warn_with_sound():
    GPIO.setmode(GPIO.BCM)
    # more stuff
    # more stuff
    # more stuff
    GPIO.cleanup()
nicolas
  • 3,120
  • 2
  • 15
  • 17

0 Answers0