From 28ccf91634ccbf42cbab6b5771924cab810e635e Mon Sep 17 00:00:00 2001 From: Adeniran John Date: Sat, 1 Nov 2025 13:51:35 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20Fix=20linting=20issues=20(import?= =?UTF-8?q?=20order=20and=20remove=20redundant=20hasattr=20check)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/params.py | 4 +-- test_depends_error.py | 63 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 3 deletions(-) create mode 100644 test_depends_error.py diff --git a/fastapi/params.py b/fastapi/params.py index c44390fb9..dd4118b08 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -790,9 +790,7 @@ class Depends: "\n✓ Correct: Depends(my_function)" "\n✗ Wrong: Depends(my_function())" ) - elif hasattr(dependency, "__class__") and hasattr( - dependency.__class__, "__call__" - ): + elif callable(dependency): # Might be an instance of a callable class error_msg += "\n\nIf you're using a callable class, make sure to pass the class itself or a callable instance." diff --git a/test_depends_error.py b/test_depends_error.py new file mode 100644 index 000000000..46d6e2ca8 --- /dev/null +++ b/test_depends_error.py @@ -0,0 +1,63 @@ +# manual_test.py +# Run this to see the improved error messages + +from fastapi import FastAPI, Depends + +print("Testing improved error messages...\n") + +def get_user(): + return {"user": "john"} + +# Test 1: Called function +print("Test 1: Using Depends(get_user()) - should show helpful error") +try: + app1 = FastAPI() + + @app1.get("/") + def route1(user = Depends(get_user())): + return user + + print("❌ No error raised (unexpected)") +except TypeError as e: + print(f"✓ Error caught: {e}\n") + +# Test 2: Nested Depends +print("Test 2: Using Depends(Depends(get_user)) - should show nested error") +try: + app2 = FastAPI() + + @app2.get("/") + def route2(user = Depends(Depends(get_user))): + return user + + print("❌ No error raised (unexpected)") +except TypeError as e: + print(f"✓ Error caught: {e}\n") + +# Test 3: String instead of callable +print("Test 3: Using Depends('not_callable') - should show type error") +try: + app3 = FastAPI() + + @app3.get("/") + def route3(user = Depends("not_callable")): + return user + + print("❌ No error raised (unexpected)") +except TypeError as e: + print(f"✓ Error caught: {e}\n") + +# Test 4: Correct usage (should work) +print("Test 4: Using Depends(get_user) correctly - should work") +try: + app4 = FastAPI() + + @app4.get("/") + def route4(user = Depends(get_user)): + return user + + print("✓ Correct usage works! No error raised.\n") +except Exception as e: + print(f"❌ Unexpected error: {e}\n") + +print("All manual tests completed!") \ No newline at end of file