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):
    ...
🌐
GitHub
github.com › sqlalchemy › sqlalchemy › issues › 5532
AttributeError: 'property' object has no attribute 'property' · Issue #5532 · sqlalchemy/sqlalchemy
August 24, 2020 - When running Alpha().instance_method(), I'm getting AttributeError: 'property' object has no attribute 'property'. That is because the type of class_.bravo is actually <class 'property'> When I do the same outside of the instance method:
Author   cuzox
Discussions

Solved: AttributeError: 'property' object has no attribute 'add’ - MyActivateHandler - Autodesk Community
Solved: I am trying to add my eventHandler to the Command event endpoint following the example outlined here, but I keep getting the following error. More on forums.autodesk.com
🌐 forums.autodesk.com
January 12, 2020
page.overlay.append - AttributeError: 'property' object has no attribute 'append'
Flet 0.22 Windows 10 The code is from the documentation Have the following code and and i am receiving AttributeError: 'property' object has no attribute 'append' on the following l... More on github.com
🌐 github.com
2
April 21, 2024
Regression in pytest 8.3.1: AttributeError: 'property' object has no attribute '__code__' on Python 3.11 when combining doctest with property decoration
a detailed description of the bug or problem you are having output of pip list from the virtual environment you are using pytest and operating system versions minimal example if possible This is su... More on github.com
🌐 github.com
4
July 22, 2024
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
🌐
Reddit
reddit.com › r/python › behavior of attributeerror in @property and __getattr__
r/Python on Reddit: Behavior of AttributeError in @property and __getattr__
April 14, 2024 -

I'm sure that many people have encountered the following (code for reproduction below) behavior: if during the execution of `@property`, an `AttributeError` is raised and the same class implements `__getattr__` then `__getattr__` is invoked with the name of the property resulting in a confusing message: `AttributeError: 'Foo' object has no attribute 'something'`. If we remove `__getattr__` then we get a more meaningful and correct message: `AttributeError: 'Foo' object has no attribute 'bar'`.

from dataclasses import dataclass

@dataclass
class Foo: val = 'foo_value'

class Test: 
    def __init__(self): 
        self.foo = Foo()

    def __getattr__(self, name):
        return getattr(self.foo, name)
    
    @property
    def something(self):
        return self.foo.bar

t = Test() t.something

The error message is misleading and the behavior catches many people (myself including) in surprise and results in many wasted hours of debugging. I've seen people recommend using a custom decorator (instead of `@property` that catches attribute error) or wrapping your `@property` bodies in `try/except`. But it seems to me that this should be dealt with on language level.

I'm trying to understand a few things:

  1. Is this behavior in Python intentional (i.e. is there a good reason) or just stems from the fact that `__getattr__` is invoked when `AttributeError` is raised when an instance attribute is accessed?

  2. If not intentional, is there a relatively easy way to detect `AttributeErrors` cause by `@property` execution in CPython? If so, why hasn't this been handled on language level?

  3. I've searched CPython issues on Github and I saw someone trying to correct documentation but couldn't find issues asking about this behavior or suggestions to fix - am I missing something?

🌐
Red Hat
access.redhat.com › solutions › 3366981
ipa-client-install fails with error AttributeError: 'property' object has no attribute 'presentTypes'. - Red Hat Customer Portal
August 9, 2024 - Unable to run "ipa-client-install", it fails with error AttributeError: 'property' object has no attribute 'presentTypes'.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-attributeerror-object-has-no-attribute
How to fix AttributeError: object has no attribute - GeeksforGeeks
July 23, 2025 - The "AttributeError: Object has no attribute" error is a common issue in Python. It occurs when we try to access an attribute of an object that doesn't exist for that object.
🌐
GitHub
github.com › sphinx-doc › sphinx › issues › 9843
AttributeError: 'property' object has no attribute 'expandtabs' · Issue #9843 · sphinx-doc/sphinx
November 12, 2021 - on Nov 12, 2021 · Issue body actions · Since 4.3.0 we see the following while reading the project sources: [2021-11-11T09:54:58.565Z] Exception occurred: [2021-11-11T09:54:58.565Z] File "<BASE>/venv/lib/python3.7/site-packages/sphinx/util/docstrings.py", line 75, in prepare_docstring [2021-11-11T09:54:58.565Z] lines = s.expandtabs(tabsize).splitlines() [2021-11-11T09:54:58.565Z] AttributeError: 'property' object has no attribute 'expandtabs' Log attached.
🌐
Autodesk Community
forums.autodesk.com › t5 › fusion-api-and-scripts-forum › attributeerror-property-object-has-no-attribute-add › td-p › 9244331
Solved: AttributeError: 'property' object has no attribute 'add’ - MyActivateHandler - Autodesk Community
January 12, 2020 - I am trying to add my eventHandler to the Command event endpoint following the example outlined here, but I keep getting the following error. Traceback (most recent call last): File/line(...), in command_var.execute.add(onCommandExecute) AttributeError: 'property' object has no attribute 'add’ Section of the code which is relevant was copied from one of the examples in the documentation (link # ------- Global variables --------- After importing libraries # Global variable used to maintain a reference to all event handlers. handlers = [] command_var = adsk.core.Command # -------- Event handle
Find elsewhere
🌐
GitHub
github.com › flet-dev › flet › issues › 3073
page.overlay.append - AttributeError: 'property' object has no attribute 'append' · Issue #3073 · flet-dev/flet
April 21, 2024 - Flet 0.22 Windows 10 The code is from the documentation Have the following code and and i am receiving AttributeError: 'property' object has no attribute 'append' on the following line page.overlay.append(pick_files_dialog) import flet a...
Author   gitmatsika
🌐
GitHub
github.com › dask › dask › issues › 3954
visualize() gives error - AttributeError: 'property' object has no attribute 'serialized' · Issue #3954 · dask/dask
September 5, 2018 - ------------------------------... 544 if not query(descriptor): 545 continue 546 ~/.local/share/virtualenvs/dask-u147dOf9/lib/python3.5/site-packages/bokeh/core/has_props.py in <lambda>(prop) 498 499 ''' --> 500 return self.query_properties_with_values(lambda prop: prop.serialized, include_defaults) 501 502 @classmethod AttributeError: 'property' object has no attribute ...
🌐
GitHub
github.com › pytest-dev › pytest › issues › 12650
Regression in pytest 8.3.1: AttributeError: 'property' object has no attribute '__code__' on Python 3.11 when combining doctest with property decoration · Issue #12650 · pytest-dev/pytest
July 22, 2024 - This is super edge-casy I am not even sure this is worth fixing but maybe the fix is simple enough? This was originally seen in scikit-learn CI scikit-learn/scikit-learn#29486 (comment) ... # test_deprecation.py import functools class deprecated: def __init__(self, reason): self.reason = reason def __call__(self, prop): @property @functools.wraps(prop) def inner(*args, **kwargs): return prop.fget(*args, **kwargs) return inner class MockClass: @deprecated("n_features_ is deprecated") @property def n_features_(self): """Number of input features.""" return 10
Author   lesteve
🌐
Lpsm
perso.lpsm.paris › ~msangnier › property.html
Confusing error message when using @property and getattr
I reproduce here a confusing error I experienced recently with Python 3 · Below is defined a simple class, called MyClass, equipped with an accessor att(self) of the attribute att and a method val(self), that simply returns the real part of att using its accessor.
🌐
GitHub
github.com › matplotlib › matplotlib › issues › 15167
matplotlib import fails · Issue #15167 · matplotlib/matplotlib
September 1, 2019 - Bug report Bug summary import matplotlib.pyplot fails with 'property' object has no attribute '__name__' Code for reproduction import matplotlib.pyplot Matplotlib version Operating ...
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.

🌐
GitHub
github.com › etingof › pyasn1 › issues › 127
AttributeError: 'property' object has no attribute 'presentTypes' · Issue #127 · etingof/pyasn1
May 22, 2018 - I have upgrade pyasn1-modules to latest & rerun to verify import package version. Before it was 0.4.5 & now its 0.4.7 [root@svpod7mgmt002 ping]# python -c 'import pyasn1; print(pyasn1.version)' 0.4.7
🌐
GitHub
github.com › run-llama › llama_index › issues › 14758
[Question]: AttributeError: 'property' object has no attribute 'context_window' · Issue #14758 · run-llama/llama_index
July 15, 2024 - Question Validation I have searched both the documentation and discord for an answer. Question I have a custom ollama llm running in local , but i'm facing the above issue when i come to query. class LiLlm(Ollama): @staticmethod def get_...
Author   18811449050
🌐
CopyProgramming
copyprogramming.com › howto › python-property-object-has-no-attribute
Python Property Object Has No Attribute: Complete Fix Guide & 2026 Best Practices - Python property object has no attribute complete fix guide
December 21, 2025 - The "AttributeError: property object has no attribute" error occurs when Python code attempts to access an attribute on a property object that doesn't exist, typically due to typos, incorrect attribute access syntax, or misunderstanding how Python's decorator works.
🌐
CodeWithHarry
codewithharry.com › blogpost › attribute-error-in-python
[Solved] Python AttributeError: object has no attribute 'X' | Blog | CodeWithHarry
Here an AttributeError occurs when attempting to use the append method on the integer object X. This is because integers do not have an append method. To handle Attribute Errors, you can use a try-except block: class Student: def __init__(self, name): self.name = name my_student = Student("Rohan") # Use a try-except block to catch the potential AttributeError.
🌐
GitHub
github.com › rkern › line_profiler › issues › 21
AttributeError: 'property' object has no attribute '__code__' · Issue #21 · rkern/line_profiler
March 20, 2015 - I'm trying to profile the following code: https://github.com/rueckstiess/mtools/blob/8ee80ac14fa1425cfbdaa7c0c0a2c69f36ecae21/mtools/util/logevent.py I have added @profile to the duration method as follows: @profile @property def duratio...
Author   victorhooi
🌐
Reddit
reddit.com › r/codinghelp › matplotlib returning: attributeerror: 'property' object has no attribute '__name__'
r/CodingHelp on Reddit: Matplotlib returning: AttributeError: 'property' object has no attribute '__name__'
January 29, 2020 -

I've built a webscraper in python (Jupyter) to pull post content from a blog and I would like to use the csv file to create a wordcloud. This is the wordcloud code I am using:

%matplotlib notebook
from os import path
import matplotlib.pyplot as plt
import random

from wordcloud import WordCloud, STOPWORDS

# Open and read blog_stuff csv file
file = open("blog_stuff.csv",'r')
text = file.read()
file.close()

# Generate WordCloud 
# !!!make sure the path for the font is correct!!!
wordcloud = WordCloud(font_path='C:/Windows/Fonts/Calibri.ttf', relative_scaling = 0.25 ).generate(text)

# Save image
plt.savefig('wordcloud.png')

# Display Image
plt.show()

I keep running into an attribute error on all of the tutorials I follow. This is the error:


AttributeError Traceback (most recent call last) <ipython-input-34-20ba22870573> in <module> ----> 1 get_ipython().run_line_magic('matplotlib', 'notebook') 2 from os import path 3 import matplotlib.pyplot as plt 4 import random 5

~\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth) 2305 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals 2306 with self.builtin_trap: -> 2307 result = fn(*args, **kwargs) 2308 return result 2309

<C:\Users\MyName\Anaconda3\lib\site-packages\decorator.py:decorator-gen-109> in matplotlib(self, line)

~\Anaconda3\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k) 185 # but it's overkill for just that one bit of state. 186 def magic_deco(arg): --> 187 call = lambda f, *a, **k: f(*a, **k) 188 189 if callable(arg):

~\Anaconda3\lib\site-packages\IPython\core\magics\pylab.py in matplotlib(self, line) 97 print("Available matplotlib backends: %s" % backends_list) 98 else: ---> 99 gui, backend = self.shell.enable_matplotlib(args.gui) 100 self._show_matplotlib_backend(args.gui, backend) 101

~\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py in enable_matplotlib(self, gui) 3382 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) 3383 -> 3384 pt.activate_matplotlib(backend) 3385 pt.configure_inline_support(self, backend) 3386

~\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in activate_matplotlib(backend) 311 matplotlib.rcParams['backend'] = backend 312 --> 313 import matplotlib.pyplot 314 matplotlib.pyplot.switch_backend(backend) 315

~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in <module> 30 from cycler import cycler 31 import matplotlib ---> 32 import matplotlib.colorbar 33 import matplotlib.image 34 from matplotlib import rcsetup, style

~\Anaconda3\lib\site-packages\matplotlib\colorbar.py in <module> 25 26 import matplotlib as mpl ---> 27 import matplotlib.artist as martist 28 import matplotlib.cbook as cbook 29 import matplotlib.collections as collections

~\Anaconda3\lib\site-packages\matplotlib\artist.py in <module> 55 56 ---> 57 class Artist(object): 58 """ 59 Abstract base class for objects that render into a FigureCanvas.

~\Anaconda3\lib\site-packages\matplotlib\artist.py in Artist() 62 """ 63 @cbook.deprecated("3.1") ---> 64 @property 65 def aname(self): 66 return 'Artist'

~\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py in deprecate(obj, message, name, alternative, pending, addendum) 180 pass 181 """ --> 182 183 def deprecate(obj, message=message, name=name, alternative=alternative, 184 pending=pending, obj_type=obj_type, addendum=addendum):

AttributeError: 'property' object has no attribute 'name'

Would any of you fine folks know how I can remedy this issue?

Edit: Removed my name from path