문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top