Search code examples
pythonbuilt-inflake8

Can a class attribute shadow a built-in in Python?


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?


Solution

  • 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'