Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop evaluation within a module

Tags:

python

module

I've gotten used to writing functions that work like this:

def f():
  if sunny:
    return
  #do non-sunny stuff

I'm trying to figure out the equivalent syntax to use within a module. I want to do something like this:

if sunny:
  import tshirt
  #do something here to skip the rest of the file
import raincoat
import umbrella
#continue defining the module for non-sunny conditions

I know I can write this as an if/else but it seems silly to indent the entire rest of my module.

I could move the rest of the code into a separate module and conditionally import it, but that seems painful.

like image 279
Paul McMillan Avatar asked Jul 02 '10 01:07

Paul McMillan


2 Answers

Separate files and extra indentation are probably reasonable given that this is a weird thing to be doing to begin with.

Depending on what you actually need, you might go ahead and process all of the module body and then delete anything that isn't appropriate at some point later.

def foo(): 
  print "foo"
def bar(): 
  print "bar"

if sunny:
  del foo
else:
  del bar
like image 93
kwatford Avatar answered Nov 03 '22 21:11

kwatford


Just in the same situation and I didn't want to indent a whole slew a code in my module. I used exceptions to stop loading a module, caught and ignored the custom exception. This makes my Python module very procedural (which I assume is not ideal), but it saved some massive code changes.

I had a common/support module, which I defined the following in:

import importlib

def loadModule(module):
    try:
        importlib.import_module(module)
    except AbortModuleLoadException:
        pass;

class AbortModuleLoadException(Exception):
    pass;

With this, if I wanted to "cancel" or "stop" loading a module, I would load the module as follows:

loadModule('my_module');

And inside my module, I can throw the following exception for a certain condition:

if <condition>:
    raise AbortModuleLoadException;
like image 44
jdknight Avatar answered Nov 03 '22 22:11

jdknight