Can a class attribute shadow a built-in in Python?
Asked Answered
S

2

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?

Salivate answered 5/1, 2022 at 17:7 Comment(0)
C
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'
Caraway answered 5/1, 2022 at 17:21 Comment(2)
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.Abdella
I accept this answer because it shows a scenario where the method would indeed shadow the built-in.Salivate
A
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.

Abdella answered 5/1, 2022 at 17:11 Comment(2)
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.Salivate
Yes, but that won't happen because open() and self.open() are different and cannot be interchangable.Abdella

© 2022 - 2024 — McMap. All rights reserved.