In addition to needing to inherit from object, properties only work on instances.

a = A()
a.db.doSomething("blah")

To make a property work on the class, you can define a metaclass. (A class is an instance of a metaclass, so properties defined on the metaclass work on the class, just as properties defined on a class work on an instance of that class.)

Answer from kindall on Stack Overflow
Top answer
1 of 3
22

In addition to needing to inherit from object, properties only work on instances.

a = A()
a.db.doSomething("blah")

To make a property work on the class, you can define a metaclass. (A class is an instance of a metaclass, so properties defined on the metaclass work on the class, just as properties defined on a class work on an instance of that class.)

2 of 3
1

You aren't using classes correctly. A class is (normally) two things:

  1. A factory for creating a family of related objects
  2. A definition of the common behaviour of those objects

These related objects are the instances of the class. Normal methods are invoked on instances of the class, not on the class itself. If you want methods that can be invoked from the class, without an instance, you need to label the methods with @classmethod (or @staticmethod).

However I don't actually know whether properties work when retrieved from a class object. I can't check right now, but I don't think so. The error you are getting is that A.db is retrieving the property object which defines the property itself, it isn't "evaluating" the property to get A.__db. Property objects have no doSomething attribute. Properties are designed to be created in classes as descriptions of how the instances of those classes work.

If you did intend to be working with an instance of A, then you'll need to create one:

my_a = A()
my_a.db.doSomething("blah")

However, this will also fail. You have not correctly written getDB as any kind of method. Normal methods need an argument to represent the instance it was invoked on (traditionally called self):

def getDB(self):
    ...

Static methods don't, but need a decorator to label them as static:

@staticmethod
def getDB():
    ...

Class methods need both an argument to receive the class they were invoked on, and a decorator:

@classmethod
def getDB(cls):
    ...
Discussions

oop - Python Attribute Error: type object has no attribute - Stack Overflow
I am new to Python and programming in general and try to teach myself some Object-Oriented Python and got this error on my lattest project: AttributeError: type object 'Goblin' has no attribute '... More on stackoverflow.com
🌐 stackoverflow.com
python - Why do I receive the following AttributeError when testing a class method with unittest: 'class' object has no attribute 'testing method'? - Stack Overflow
For the sake of practicing to code, I am trying to program a very simple game. When trying to run a test on a (private) class method, I receive the following error: AttributeError: 'LivingBeing' ob... More on stackoverflow.com
🌐 stackoverflow.com
python - "AttributeError: 'property' object has no attribute 'get'" when using Depends in FastAPI - Stack Overflow
To implement authentication for a FastAPI endpoint, I want to make use of the Depends functionality offered in the latest versions (>=0.95) of FastAPI. I have tried several ways to implement it ... More on stackoverflow.com
🌐 stackoverflow.com
python - AttributeError: 'cached_property' object has no attribute 'setter' - Stack Overflow
I'm using the functools.cached_property to memoize some functions. but it seems not to be supporting setter. for example class User @cached_property def name(self): return self._name ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-attributeerror-object-has-no-attribute
How to fix AttributeError: object has no attribute - GeeksforGeeks
July 23, 2025 - Inside the constructor, we are initializing the name attribute of the Dog object with the value provided as name. Then we are creating a Dog object named my_dog with the name "Buddy". But in the end we are trying to access the non-existent attribute "breed". That is why we get an "AttributeError".
🌐
Delft Stack
delftstack.com › home › howto › python › python object has no attribute
How to Fix Object Has No Attribute Error in Python | Delft Stack
February 2, 2024 - Everything in Python is an object, and all these objects have a class with some attributes. We can access such properties using the . operator. This tutorial will discuss the object has no attribute python error in Python. This error belongs to the AttributeError type.
Find elsewhere
Top answer
1 of 1
2

When using Depends(), you just pass the name of the dependency function within the brackets (i.e., don't call it directly, just pass it as a parameter to Depends()). As described in the documentation:

Let's first focus on the dependency.

It is just a function that can take all the same parameters that a path operation function can take.

And it has the same shape and structure that all your path operation functions have.

You can think of it as a path operation function without the "decorator" (without the @app.get("/some-path")).

And it can return anything you want.

Thus, any other parameters that your dependency function takes, you simply need to declare them in that function and not passing them through Depends(). Same applies to the Request object. FastAPI will analyze the parameters for the dependency, and process them in the same way as the parameters for a path operation function (also known as endpoint), including sub-dependencies.

Hence, your endpoint should look like this:

@app.get("/")
async def home(user: Annotated[User, Depends(authenticate_request)]):
    pass

and your authenticate_request dependency function should be as follows:

def authenticate_request(request: Request) -> User:
    pass

Additional Information 1

Instead of a "callable" function, one could also use a Python class instead as a dependency, as Python classes are also callable.

One not only can they use a "callable" dependency class, but also a "callable" instance of that dependency class, which would allow them to initially pass fixed content when creating the instance of the class, as well as pass additional parameters and sub-dependencies when the endpoint is called.

The __init__ method in the example below is used to declare the parameters of the instance that we can use to "parameterize" the dependency (the fixed content). FastAPI won't ever touch or care about __init__, it is used directly in the code when creating the instance of the class.

The __call__ method, on the other hand, is what FastAPI will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your endpoint, when it will later be called.

Hence, in the example below, fixed_content is the attribute used to "parameterize" the dependency, while q is the additional query parameter to pass a value for, when a client is calling the endpoint.

Example

class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
        if q:
            return self.fixed_content in q
        return False


checker = FixedContentQueryChecker("bar")


@app.get("/query-checker/")
async def read_query_check(fixed_content_included: bool = Depends(checker)):
    return {"fixed_content_in_query": fixed_content_included}

A context manager in dependencies could be used as well.

Additional Information 2

One should also be aware that, as described here:

You can't use Depends in your own functions, it has to be in FastAPI functions, mainly routes. You can, however, use Depends in your own functions when that function is also a dependency, so could can have a chain of functions.

For example, a route uses Depends to resolve a get_current_user, which also uses Depends to resolve get_db, and the whole chain will be resolved. But, if you then call get_current_user without using Depends, it won't be able to resolve get_db.

What I do is get the DB session from the route and then pass it down through every layer and function. I believe this is also better design.

Hence, FastAPI does not resolve Depends at random locations in the code, but only as part of an existing Depends hierarchy from the endpoint/route function or other Dependencies.

🌐
GeeksforGeeks
geeksforgeeks.org › python-attributeerror
Python: AttributeError - GeeksforGeeks
January 3, 2023 - # Python program to demonstrate # AttributeError class Geeks(): def __init__(self): self.a = 'GeeksforGeeks' # Driver's code obj = Geeks() # Try and except statement for # Exception handling try: print(obj.a) # Raises an AttributeError print(obj.b) # Prints the below statement # whenever an AttributeError is # raised except AttributeError: print("There is no such attribute") ... Note: To know more about exception handling click here. ... PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. Attributes: Attribute defines the various property of an object, element or file.
🌐
Real Python
realpython.com › ref › builtin-exceptions › attributeerror
AttributeError | Python’s Built-in Exceptions – Real Python
>>> class Dog: ... def bark(self): ... Dog class doesn't have a 'meow' method. Every Python object will raise an AttributeError when you attempt to access a non-existent attribute on it....
🌐
AskPython
askpython.com › home › how to fix the ‘class’ object has no ‘attribute_name’ error in python
How to Fix the 'Class' object has no 'attribute_name' Error in Python - AskPython
April 10, 2025 - class Example: pass obj = Example() print(obj.attribute_name) # Raises AttributeError ... The example here states that missing the attribute named ‘attribute_name’ while initialising the class ‘Example’ raises an Attribute Error when called by the object of the same class. Thus it is important to watch for attributes before calling them via objects. ... Inheritance is the property of a child class inheriting the properties of the parent class.
🌐
JanBask Training
janbasktraining.com › community › python-python › why-am-i-getting-attributeerror-object-has-no-attribute
Why am I getting AttributeError: Object has no attribute | JanBask Training Community
April 17, 2021 - The "AttributeError: Object has no attribute" error occurs in Python when you try to access or call an attribute or method that does not exist on an object.
🌐
Rollbar
rollbar.com › home › how to fix attributeerror in python
How to Fix AttributeError in Python | Rollbar
October 17, 2022 - The Python AttributeError is raised when an invalid attribute reference is made. This can happen if an attribute or function not associated with a data type is referenced on it.
🌐
Django Forum
forum.djangoproject.com › using django › forms & apis
Don't know how to fix AttributeError: 'function' object has no attribute 'pk' when trying to create new users from registration form - Forms & APIs - Django Forum
September 2, 2023 - Hi, I’m still very new to Python and Django. I am trying to create a working registration page and i get this error when submitting the form. I can’t find this error when looking on stack overflow or the forum and don’t know how to fix this issue. I copied the views and models code here.
Top answer
1 of 2
83

No, autospeccing cannot mock out attributes set in the __init__ method of the original class (or in any other method). It can only mock out static attributes, everything that can be found on the class.

Otherwise, the mock would have to create an instance of the class you tried to replace with a mock in the first place, which is not a good idea (think classes that create a lot of real resources when instantiated).

The recursive nature of an auto-specced mock is then limited to those static attributes; if foo is a class attribute, accessing Foo().foo will return an auto-specced mock for that attribute. If you have a class Spam whose eggs attribute is an object of type Ham, then the mock of Spam.eggs will be an auto-specced mock of the Ham class.

The documentation you read explicitly covers this:

A more serious problem is that it is common for instance attributes to be created in the __init__ method and not to exist on the class at all. autospec can’t know about any dynamically created attributes and restricts the api to visible attributes.

You should just set the missing attributes yourself:

@patch('foo.Foo', autospec=Foo)
def test_patched(self, mock_Foo):
    mock_Foo.return_value.foo = 'foo'
    Bar().bar()

or create a subclass of your Foo class for testing purposes that adds the attribute as a class attribute:

class TestFoo(foo.Foo):
    foo = 'foo'  # class attribute

@patch('foo.Foo', autospec=TestFoo)
def test_patched(self, mock_Foo):
    Bar().bar()
2 of 2
2

There is only a create kwarg in patch that, when set to True, will create the attribute if it doesn't exist already.

If you pass in create=True, and the attribute doesn’t exist, patch will create the attribute for you when the patched function is called, and delete it again after the patched function has exited.

https://docs.python.org/3/library/unittest.mock.html#patch

🌐
Net Informations
net-informations.com › python › err › attr.htm
AttributeError: 'module' object has no attribute 'main'
An attribute in Python means some property that is associated with a particular type of object . In other words, the attributes of a given object are the data and abilities that each object type inherently possesses . Attribute errors in Python are generally raised when you try to access or ...