简体   繁体   中英

Missing attributes are not caught by the Python supported IDEs

Coming from a Java/C# background Developers are used to rely on the IDEs to tell and not let them run their code if an obvious bug is present (eg trying to access an nonexistent attribute from module/class).

In this simplest example I came up with, someone changed Customer class (see # Step 1 ) and didn't refactor the rest of the project which will eventually throw an uncaught exception (see # Step 3 ):

from threading import Thread, Event
from random import randrange
import time

class Customer:
    def __init__(self, full_name, address, email):
        self.full_name = full_name
        self.address = address

        # Step 1 - For some reason (e.g. refactoring) someone decided to comment out/rename/remove the email attribute.
        #self.email = email

def my_long_running_task():

    # Step 2 - Wait for a user request to print its email with a 20% chance it will happen every second in this example. 
    # But in real life this could take hours or days until it's triggered since we don't control the user.
    while True:
        if randrange(5) == 1:
            # Step 3 - Once triggered, this will thrown exception: AttributeError: 'Customer' object has no attribute 'email'
            print("Email:" + customer1.email)
        time.sleep(1)

if __name__ == '__main__':
    customer1 = Customer("Adam", "1 Street Lower", "adam@email.com")
    print("Full name: " + customer1.full_name)
    print("Address:" + customer1.address)

    my_long_running_task()

Even if the Developer did test the script it doesn't mean it's bug free and the exception above will be thrown at a random point in time while in production.

Unit Testing would help but to enforce 100% code coverage is considered unreasonable and a bad practice as it lowers the quality of the actual tests.

VS Code and PyCharm are not flagging the missing reference/attribute customer1.email . Am I missing any extension/setting? Any suggestion/approach?

对于 VS Code,您需要安装像 PyLint 或 mypy 这样的 linter 来捕获这种警告。

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