473,837 Members | 1,778 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

setattr and getattr, when to use?

Why are these functions there? Is it somehow more idiomatic to use
than to do obj.field ?
Is there something you can with them that you can't by obj.field
reference?
Aug 23 '08 #1
4 10491
On Aug 22, 8:50*pm, maestro <notnorweg...@y ahoo.sewrote:
Why are these functions there? Is it somehow more idiomatic to use
than to do obj.field ?
Is there something you can with them that you can't by obj.field
reference?
You can generate them dynamically from strings. In some cases you
don't know until runtime what attributes you want to pull:

def show_insides(ob j):
for attr in dir(obj):
print "Attribute %r: %r" % (attr, getattr(obj, attr))

class hello(object):
a = 1
b = 2

class goodbye(object) :
c = 1
d = 500
print show_insides(he llo)
(...15 builtins...)
Attribute 'a': 1
Attribute 'b': 2

print show_insides(go odbye)
(...15 builtins...)
Attribute 'c': 1
Attribute 'd': 500

In this case, you can see that we pull the attributes of an object
using dir(), which yields a list of strings, then pull each attribute
we discover.
Aug 23 '08 #2
On Aug 22, 10:17*pm, Jason Scheirer <jason.schei... @gmail.comwrote :
On Aug 22, 8:50*pm, maestro <notnorweg...@y ahoo.sewrote:
Why are these functions there? Is it somehow more idiomatic to use
than to do obj.field ?
Is there something you can with them that you can't by obj.field
reference?

You can generate them dynamically from strings. In some cases you
don't know until runtime what attributes you want to pull:

def show_insides(ob j):
* for attr in dir(obj):
* * print "Attribute %r: %r" % (attr, getattr(obj, attr))

class hello(object):
* *a = 1
* *b = 2

class goodbye(object) :
* *c = 1
* *d = 500

print show_insides(he llo)
(...15 builtins...)
Attribute 'a': 1
Attribute 'b': 2

print show_insides(go odbye)
(...15 builtins...)
Attribute 'c': 1
Attribute 'd': 500

In this case, you can see that we pull the attributes of an object
using dir(), which yields a list of strings, then pull each attribute
we discover.
Might I add: avoid doing this if you don't have to. obj.field is the
way to go about getting your object attributes 95% of the time. The 5%
of your time when you are doing metaprogramming or other abuses of the
object system are when you use get/setattr.
Aug 23 '08 #3
On Fri, 22 Aug 2008 20:50:17 -0700, maestro wrote:
Why are these functions there? Is it somehow more idiomatic to use than
to do obj.field ?

Heavens no!!! Using setattr and getattr is *less* idiomatic.

Is there something you can with them that you can't by obj.field
reference?
Absolutely. Consider:

class Foo(object):
pass

foo = Foo()
setattr(foo, "x y", 1)
print getattr(foo, "x y")

That's probably an abuse of setattr/getattr, but there are times where
you might not know the name of the attribute until runtime, so you can't
write foo.attr since you don't know what to write in place of attr.
That's where setattr and getattr (as well as delattr and hasattr) come
into play.

--
Steven
Aug 23 '08 #4
Jason Scheirer a écrit :
(snip)
The 5%
of your time when you are doing metaprogramming or other abuses of the
object system are when you use get/setattr.
What makes you label "metaprogrammin g" and get/setattr as "abuses" ???
Aug 26 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2018
by: Gerson Kurz | last post by:
I stumbled across this (while using my homebrewn enum class): class test: pass instance = test() setattr(instance, "THIS :*2+~# IS OBVIOUSLY INVALID", 123) I would've expected some kind of error message here when calling setattr(); after all, its not a regular attribute? Plus, documentation
4
1471
by: Alex | last post by:
I apologize for asking maybe a very trivial question. I have a new class object A with slots. One of the slots is, for example, object spam. Object spam, in turn, also has slots and one of them is attribute eggs. I need to assign a new value to eggs. In other words, I need to perform the following: A.spam.eggs=newValue The problem is that I have only a string s='spam.eggs' with which to work, so I cannot write an expression written...
8
1907
by: Steven D'Aprano | last post by:
I came across this unexpected behaviour of getattr for new style classes. Example: >>> class Parrot(object): .... thing = .... >>> getattr(Parrot, "thing") is Parrot.thing True >>> getattr(Parrot, "__dict__") is Parrot.__dict__ False
4
3691
by: Emin | last post by:
Dear experts, I got some unexpected behavior in getattr and copy.deepcopy (see transcript below). I'm not sure if this is actually a bug in copy.deepcopy or if I'm doing something too magical with getattr. Comments would be appreciated. Thanks, -Emin
10
2016
by: Paulo da Silva | last post by:
Hi! In a class C, I may do setattr(C,'x',10). Is it possible to use getattr/setattr for variables not inside classes or something equivalent? I mean with the same result as exec("x=10"). Thanks.
0
1204
by: Nathan Harmston | last post by:
Hi, I m trying to implement an object which contains lazy" variables. My idea is to alter the getattr and the setattr methods. However I keep on getting a recursion error. My idea is that the lazy variable can be stored in a variety of places, Database, PyTables etc. The lazy variable is a large variable and so I dont want to hold it in memory all of the time, I d rather just get it when needed and then store it for future work. Most...
6
4298
by: Donn Ingle | last post by:
Hi, Here's some code, it's broken: class Key( object ): def __init__(self): self.props = KeyProps() def __getattr__(self, v): return getattr( self.props,v ) def __setattr__(self,var,val):
0
1388
by: John Nagle | last post by:
Just noticed, again, that getattr/setattr are ASCII-only, and don't support Unicode. SGMLlib blows up because of this when faced with a Unicode end tag: File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag method = getattr(self, 'end_' + tag) UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 46: ordinal not in range(128)
4
1402
by: Rotlaus | last post by:
2 weeks ago i asked for a etended getattr() which worked really fine, but now i would love to have a extended setattr() as well. Lets assume i have some classes: class A(object): def __init__(self): self.B = B() class B(object):
0
9846
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9691
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10891
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10638
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9418
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7009
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5677
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
4054
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3128
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.