简体   繁体   中英

Overwriting built-in function in Python

What could possibly go wrong if I unintentionally overwrite/mask build-in function in Python?

Can I experience anything worse than the obvious pitfall of accessing a local function instead of a built-in function?

For example:

def max(a, b):
  pass

class MyCompileTool(object):
    def __init__(self, id):
        self.id = id

    def compile(self):
        min = "3.4.4"
        ...

Even in some official modules: argparse.add_argument(..., type, ...)

You do not overwrite builtin min here, you just create a min local, which will be preferred if subsequent code of compile will contain calls to min :

class MyCompileTool(object):
    ...

    def compile(self):
        min = "3.4.4"
        x = min(1, 2)
        #   ^^^ "3.4.4".__call__(1, 2)
        #   This will throw exception because strings doesn't have __call__
x = min(3, 4)
#   ^^^ __builtins__.min

To shadow min in entire module, do that in global namespace:

min = "3.4.4"
# Now all calls of min will go to that string

class MyCompileTool(object):
     pass

For more information on how names are resolved in Python, check documentation: 4.1. Naming and binding

In this particular situation, there probably isn't much that can/will go wrong. You're just shadowing min with a local variable in your method, so you're probably not going to do much damage. In general though, you could see something like this:

>>> min = "3.4.4"
>>> x = min(3, 4, 5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>>

This might confuse you or (even worse) it might confuse the person who has to go in and support your code later. It would be even worse if you did it globally, like:

min = "3.4.4"

def main():
    x = min(3, 4, 5)

Overall, it's bad practice. Don't do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM