Questions tagged [getattr]

getattr is a Python built-in function used to access a named attribute on an object.

The function's schematics are as follows:

getattr(object:object, name:str[, default:object]) -> value

where object is the object, name is the named attribute, and default, if supplied, is the default value to return if the attribute can not be found. If default is not supplied and the object can not be found, an AttributeError is thrown.

Below is a demonstration of the function's features:

>>> class Test:
...     def __init__(self):
...         self.attr = 1
...
>>> myTest = Test()
>>> getattr(myTest, 'attr')
1
>>> getattr(myTest, 'attr2', 'No attribute by that name')
'No attribute by that name'
>>> getattr(myTest, 'attr2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Test instance has no attribute 'attr2'
>>>
378 questions
1
vote
1 answer

Too many getattr requests for file info when using nfs

I'm sharing a folder using nfs on a Linux system. It's very slow, and I found that there are many getattr requests. After I mount my shared nfs folder on another machine, I'm trying to copy the files out. It's very slow. What I found via tcpdump is…
d9liang
  • 11
  • 1
  • 2
1
vote
1 answer

Failing to get attribute value in Python

I'm trying to code a scraper for a website and so far I was able to scrape the general information I need but the specific attribute value I am trying to obtain from that information is returning with none even though there are clearly values there.…
CodeOrDie
  • 41
  • 1
  • 8
1
vote
1 answer

C# Get Access Properties

I would like to call function attribute (and also type) by it's name. In python this goes something like this: import time method_to_call = getattr(time, 'clock') # time.clock() result = method_to_call() print(result) But what about C# and…
mikazz
  • 159
  • 1
  • 11
1
vote
1 answer

__getattr__ special method

Why does hasattr() return boolean True below? 'bar' attribute is not set anywhere in the code. Thanks class AttrClass(object): def __getattr__(self, name): pass data = AttrClass() print('Current __dict__: ', data.__dict__) print('Does…
user1972031
  • 547
  • 1
  • 5
  • 19
1
vote
2 answers

Cannot update mutable instance attributes when __setattr__ and __getattribute__ are overridden in python

I have inherited a bunch of legacy code and have run into a bit of a breaking issue. I believe the idea attempted here was to use a containerized cache such as redis to hold certain attributes to be shared across many processes. Apart from whether…
Kyle
  • 11
  • 1
1
vote
0 answers

Given a python object, how can we get a complete list of everything that object has direct handles/references to?

Suppose we are handed a python object. We have no earthly idea where it came from, or what it contains. By calling various functions on the object, how can we coax out a definitive list of names for data the object has references to? I am only…
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
1
vote
0 answers

"Unbound Local Error" in a decorator

I'm getting an error that has me pretty stumped. #! /usr/bin/env python3 from sys import modules from inspect import isclass from functools import partial from abc import abstractmethod from abc import ABC as…
Anthony
  • 1,015
  • 8
  • 22
1
vote
3 answers

How to use getattr to call a string as an attribute?

import pandas as pd def test_run(): for symbol in ['nugt', 'soxs']: for stat in ['max', 'min', 'mean']: print(f"{stat} Close") print(symbol, get_stat(symbol, stat)) def get_stat(symbol, stat): df =…
EMZ
  • 41
  • 3
1
vote
3 answers

Adding custom objects ignores __getattr__ with operators

I am trying to create a custom object that passes all non-existent method calls down to a member attribute. This works under normal custom method invocations, but fails when attempting to call arithmetic operators. Below is a console snippet of an…
Yos233
  • 2,396
  • 2
  • 15
  • 15
1
vote
0 answers

UserWarning when adding descriptive information to a dataframe that is an attribute

I have multiindex dataframe that is actually an attribute and I am looking to store the index names using the following command: getattr(self, attrdfname).__idxnames__ = getattr(self, attrdfname).index.names It raises the following error:…
marco
  • 129
  • 1
  • 6
1
vote
3 answers

python __getattr__ help

Reading a Book, i came across this code... # module person.py class Person: def __init__(self, name, job=None, pay=0): self.name = name self.job = job self.pay = pay def lastName(self): return…
1
vote
1 answer

Python: How to dynamically get kwargs from __getattr__

Context: I’m trying to build a simple (read-only) python API client for a storage product dynamically. Situation: The api server has endpoints like this: [GET] /monitor/host?nodeId=xxx[®ion=xxx] [GET] /monitor/nodelist?[region=xxx] [GET]…
Romero Junior
  • 243
  • 3
  • 11
1
vote
2 answers

How to pass a string as an object to getattr python

I have a number of functions that need to get called from various imported files. The functions are formated along the lines of this: a.foo b.foo2 a.bar.foo4 a.c.d.foo5 and they are passed in to my script as a raw string. I'm looking for a clean…
Indigo
  • 962
  • 1
  • 8
  • 23
1
vote
4 answers

getattr lookup fails for instance of class python

I'm doing an exercise in which you're supposed to calculate a score of how classy your items are. A tophat gives you 2 points, a bowtie gives you 4 points and a monocle gives you 5 points. I've initiated a dictionary with these items on each class…
Gwater17
  • 2,018
  • 2
  • 19
  • 38
1
vote
0 answers

Why does lib.__dict__(vars) only show an object after runnning hasattr or getattr?

Here is the example code: import ctypes.util from ctypes import CDLL path = ctypes.util.find_library('crypto') lib = CDLL(path) hasattr(lib, 'EVP_get_cipherbyname') #only run this line or getattr, #the print(lib.__dict__) show the…
Edwin
  • 71
  • 1
  • 1
  • 3