using the filter function within class return error

Steven D'Aprano steve at
Fri Nov 2 19:21:03 CET 2007

On Fri, 02 Nov 2007 09:42:17 -0700, david.katkowski wrote:

> I'm trying to use the __builtin__ filter function within a class;
> however, I receive the following error:
> NameError: global name 'MajEthnic' is not defined
> The line of code is: EthMaj = filter(self.MajEthnic,flist)
> So, I'm trying to use the MajEthnic function to filter the list flist.
> Any ideas?

Yes, many.

The first idea is: the exception that you get tells you what's wrong. You 
should pay attention and define MajEthnic, just as it says.

My second idea is that you're probably giving us incorrect information. I 
can't think of any possible way for the line of code you quote to give 
the NameError you say it does. I can think of how it might give a 
different NameError:

class Parrot(object):
    flist = [1, 2, 3]
    EthMaj = filter(self.MajEthnic, flist)

or possible an AttributeError:

class Parrot(object):
    def method(self, flist):
        EthMaj = filter(self.MajEthnic, flist)

but not the exception that you quote.

My third idea is that if you want better help, you should provide better 
information. Please quote the entire traceback, not paraphrasing it, 
unless it is excessively long, in which case you can trim some of the 
extra stack trace (but tell us you've done so!). Please ensure you are 
actually quoting the correct line of code that generates the exception.

My fourth idea is that your subject line is incorrect. The filter 
function does not RETURN an error, it RAISES an error. Using correct 
terminology is important.

Although technically, it is just barely possible that filter actually is 
*returning* an exception, or at least a list containing an exception, if 
flist looks something like this:

flist = [NameError("global name 'MajEthnic' is not defined"), 0, 1, 2]

Exceptions are objects like any other, and can be returned, although that 
would be extremely unusual, and not something that "just happens" -- you 
have to work at it!


More information about the Python-list mailing list