Imports and methods fall in the same namespace?

Bug #1675659 reported by Lele Gaifax
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
Pyflakes
Confirmed
Undecided
Unassigned

Bug Description

Consider the following script:

import bar

class Foo:
    def bar(self):
        pass

Pyflakes emits:

$ pyflakes foo.py
foo.py:1: 'bar' imported but unused
foo.py:4: redefinition of unused 'bar' from line 1

Both disappears if `bar` is actually used, so the following is clean:

import bar

class Foo:
    def bar(self):
        pass

coffee = bar.Espresso()

Revision history for this message
asmeurer (asmeurer) wrote :

The error seems correct to me. If you had

import bar

class Foo:
    a = bar

then Foo().a would be bar (the module). If you had

class Foo:
    def bar(self):
        pass

    a = bar

then Foo().a would be bar (the method). So the method does override the imported name in the class namespace, which pyflakes warns about (but only if the name is unused, to avoid false positives).

Revision history for this message
Lele Gaifax (lelegaifax) wrote :

Well, I don't agree with your argument, but if that's instead valid, then I would
expect that a very similar case, that is

def a():
    pass

class A:
    def a(self):
        pass

should emit the same error instead of the current happy mood, and even

a = 1

def b():
    a = 2

should "warn" me about the override of a global symbol within the function namespace,
instead of the current and IMHO correct warning about unused assignment.

In any case, the fact that the error "disappear" as soon as I use the imported symbol
seems wrong: the class method is still overriding the global symbol.

Revision history for this message
asmeurer (asmeurer) wrote :

I think pyflakes automatically assumes functions and module level variables are "used" because they could just be defined to be importable from other modules.

Revision history for this message
Phil Frost (bitglue) wrote :

Report seems legit to me. In the example:

import bar

class Foo:
    def bar(self):
        pass

the bar import is unused, and there should remain an error about that. But defining a bar function inside the class scope does not seem like an error. Pyflakes does not emit errors for shadowing global variables, imports or otherwise, unless it's done such that something which was imported can not possibly be used. Like this:

$ pyflakes
import foo
foo = 1
<stdin>:2: redefinition of unused 'foo' from line 1

I'm vaguely remembering there was some implementation reason for this bug, and maybe it was too difficult to fix. But that was years ago...worth at least investigating.

Changed in pyflakes:
status: New → Confirmed
To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.