6

If have some code like this:

class Foo():
   def open(self, bar):
       # Doing some fancy stuff here, i.e. opening "bar"
       pass

When I run flake8 with the flake8-builtins plug-in I get the error

A003 class attribute "open" is shadowing a python builtin

I don't understand how the method could possibly shadow the built-in open-function, because the method can only be called using an instance (i.e. self.open("") or someFoo.open("")). Is there some other way code expecting to call the built-in ends up calling the method? Or is this a false positive of the flake8-builtins plug-in?

SebDieBln
  • 3,303
  • 1
  • 7
  • 21

2 Answers2

6

Not really a practical case, but your code would fail if you wanted to use the built-it functions on the class level after your shadowed function has been initialized:

class Foo:
    def open(self, bar):
        pass

    with open('myfile.txt'):
        print('did I get here?')

>>> TypeError: open() missing 1 required positional argument: 'bar'

The same would also be true with other built-in functions, such as print

class Foo:
    def print(self, bar):
        pass

    print('did I get here?')

>>> TypeError: print() missing 1 required positional argument: 'bar'
Wondercricket
  • 7,651
  • 2
  • 39
  • 58
  • That is true, but the functions made in a class are used for class objects. `self.open()` and `open()` are different, so there is no issue. – Cameron Jan 05 '22 at 17:27
  • I accept this answer because it shows a scenario where the method would indeed shadow the built-in. – SebDieBln Jan 05 '22 at 22:08
2

You shouldn't have a problem with the code. As long as the function is referenced with self.open() and not open(), it should work. Just make sure the class does not already have an open() function.

Cameron
  • 389
  • 1
  • 9
  • It's more the other way around that I am worried about: writing `open()` and ending up calling the method instead of the built-in function. – SebDieBln Jan 05 '22 at 17:27
  • 1
    Yes, but that won't happen because `open()` and `self.open()` are different and cannot be interchangable. – Cameron Jan 05 '22 at 17:33