2

I have some Python code from a course I'm taking and am seeing errors in some of the files that test for support of particular features and won't try to use them if the features are not present. In my case, I don't have the feature available, so the code after the conditional shouldn't get executed.

These sections shouldn't manifest as runtime errors if the code is actually reached.

For instance:

def __call__(self, *args):
    if not 'SIGALRM' in dir(signal):
        return self.function(*args)
    old = signal.signal(signal.SIGALRM, self.handle_timeout)
    signal.alarm(self.timeout)
    try:
        result = self.function(*args)
    finally:
        signal.signal(signal.SIGALRM, old)
    signal.alarm(0)
    return result

I get Undefined variable from import: SIGALRM, Undefined variable from import: alarm, etc. errors in the body, but the method would have returned if SIGALRM wasn't supported.

Is there a way to suppress errors in these sections?

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246

2 Answers2

0

It ain't pretty, but you can either suppress all of the undefined variable (and other) errors by setting preferences at:

Preferences -> PyDev -> Editor -> Code Analysis -> Undefined -> Undefined Variable From Import -> Ignore

Or alternately, add comments to the end of each line such as:

#@UnresolvedImport

#@UnusedVariable

There are others you can test with autocomplete that should be self-explanatory.

Here's how to selectively suppress errors in the question's code:

def __call__(self, *args):
    if not 'SIGALRM' in dir(signal):
        return self.function(*args)
    old = signal.signal(signal.SIGALRM, self.handle_timeout) #@UndefinedVariable
    signal.alarm(self.timeout) #@UndefinedVariable
    try:
        result = self.function(*args)
    finally:
        signal.signal(signal.SIGALRM, old) #@UndefinedVariable
    signal.alarm(0) #@UndefinedVariable
    return result
Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
0

How about using getattr and hasattr instead? Maybe something like the following:

def __call__(self, *args):
    if not hasattr(signal, 'SIGALRM'):
        return self.function(*args)

    sigalrm = getattr(signal, 'SIGALRM')
    alarm = getattr(signal, 'alarm')

    old = signal.signal(sigalrm, self.handle_timeout)
    alarm(self.timeout)
    try:
        result = self.function(*args)
    finally:
        signal.signal(sigalrm, old)
    alarm(0)
    return result
Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
  • That's certainly cleaner--though I was initially just looking for a way to suppress warnings. This is code I didn't write. I've only been using Python for a couple of days now, and I have to say I'm really not a fan of dynamic types because of this issue and many others I've already run into (namely making it difficult or impossible for IDEs to make much sense of your code). – Jeff Axelrod Oct 13 '12 at 21:24