انتقل للمحتوى
Robo EgyptRobo Egypt
تقدّمك في الجزء0 من 24
الدرس 5.2 · الكود والأرقام⏱ 12 دقيقة
الفصل 5: Static Analysis و Code Review: امسك الغلطة قبل ما تشتغل

تجربة: 9 مشاكل في 20 سطر

report.py شكله سليم، وأغلب الوقت هيشتغل.

  • extra=[]: ليستة بتتشارك بين النداءات.
  • except: فاضية بتبلع كل الأخطاء.
  • دالة ممكن ترجّع None والكود مش واخد باله.

الشرح بالتفصيل

import os, json


def average(grades: list[int]) -> float:
    return sum(grades) / len(grades)


def find_student(students: list[dict], name: str) -> dict | None:
    for s in students:
        if s["name"] == name:
            return s


def report(students: list[dict], name: str, extra=[]) -> str:
    s = find_student(students, name)
    extra.append(name)
    try:
        avg = average(s["grades"])
    except:
        avg = 0
    if avg == None:
        return "no grades"
    return f"{s['name']}: {avg:.1f}"
Terminal🖥 بيشتغل في برنامج روبو لاب على الكمبيوتر · النتيجة من الكتاب
ruff check --select F,E,B report.py
mypy report.py
النتيجة:
E401 Multiple imports on one line                         --> report.py:1:1
F401 `os` imported but unused                              --> report.py:1:8
F401 `json` imported but unused                            --> report.py:1:12
B006 Do not use mutable data structures for argument defaults  --> report.py:14:51
E722 Do not use bare `except`                              --> report.py:19:5
E711 Comparison to `None` should be `cond is None`         --> report.py:21:15
Found 6 errors.

report.py:8: error: Missing return statement  [return]
report.py:18: error: Value of type "dict[Any, Any] | None" is not indexable  [index]
report.py:23: error: Value of type "dict[Any, Any] | None" is not indexable  [index]
Found 3 errors in 1 file (checked 1 source file)

أخطر 3: (1) B006: الـ extra=[] بتتعمل مرة واحدة بس وقت تعريف الدالة، فكل نداء بيضيف على نفس الـ list، والـ list بتكبر للأبد. (2) E722: الـ except العريان بيبلع كل حاجة، حتى الطالب اللي مش موجود (None)، فالتقرير بيقول «متوسط 0» بدل «الطالب مش موجود». (3) mypy شاف إن find_student ممكن ترجّع None، وإنك بتستخدم النتيجة كأنها dict من غير ما تتأكد. ده بالظبط الـ «billion-dollar mistake» اللي Tony Hoare اعتذر عنه (اختراع الـ null سنة 1965).

ملاحظةالأدوات دي (git و pytest و ruff…) بتشتغل في برنامج روبو لاب على الكمبيوتر: دوس «🖥 شغّل على الجهاز».
خلصت الدرس؟ علّم عليه عشان تقدّمك يتحسب.