473,803 Members | 4,392 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getattr/setattr q.

Hi!

In a class C, I may do setattr(C,'x',1 0).

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.
Apr 3 '07 #1
10 2012
Paulo da Silva wrote:
In a class C, I may do setattr(C,'x',1 0).

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").
If you're at the module level, you can do::

globals()['x'] = 10

If you're inside a function, you probably want to look for another way
of doing what you're doing.

What's the actual task you're trying to accomplish here?

STeVe
Apr 3 '07 #2
Paulo da Silva <ps********@eso tericaX.ptXwrit es:
In a class C, I may do setattr(C,'x',1 0).
That would set an attribute on the class C, shared by all instances of
that class.

If you want to set an attribute on an instance, you need to do so on
the instance object::
>>class Foo(object):
... def __init__(self):
... setattr(self, 'bar', 10)
...
>>Foo.bar
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: type object 'Foo' has no attribute 'bar'
>>spam = Foo()
spam.bar
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").
"Variables not inside classes or functions" are attributes of the
module (so-called "global" attributes). Thus, you can use setattr on
the module object::
>>import sys
>>def foo():
... this_module = sys.modules[__name__]
... setattr(this_mo dule, 'bar', 10)
...
>>bar
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'bar' is not defined
>>foo()
bar
10

--
\ "I'm beginning to think that life is just one long Yoko Ono |
`\ album; no rhyme or reason, just a lot of incoherent shrieks and |
_o__) then it's over." -- Ian Wolff |
Ben Finney
Apr 3 '07 #3
On Apr 2, 10:08 pm, Paulo da Silva <psdasil...@eso tericaX.ptXwrot e:
Is it possible to use getattr/setattr for variables not inside
classes...?
What does the python documentation say about the definition of
setattr()?

Apr 3 '07 #4
On Tue, 03 Apr 2007 05:08:42 +0100, Paulo da Silva wrote:
Hi!

In a class C, I may do setattr(C,'x',1 0).

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").
Yes, but you shouldn't unless you really need to. You're better off
rethinking your algorithm.

If you think you really need to, you probably don't.

If you *really* think you really need to, you might.

>>x
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
>>globals()['x'] = 5
x
5
Note that there is also a function locals(), but it doesn't work as you
might expect:

>>def f():
.... locals()['x'] = 99
.... print x
....
>>f()
5

--
Steven D'Aprano

Apr 3 '07 #5
7stud escreveu:
On Apr 2, 10:08 pm, Paulo da Silva <psdasil...@eso tericaX.ptXwrot e:
>Is it possible to use getattr/setattr for variables not inside
classes...?

What does the python documentation say about the definition of
setattr()?
I didn't read the full python documentation, yet! I hope to survive
until then :-)
In the meanwhile, I searched google for setattr python but all
references I could see were about X.foo type.

One more "RTFM culture" response ...

Thanks.
Paulo

Apr 3 '07 #6
Steven Bethard escreveu:
Paulo da Silva wrote:
....
If you're at the module level, you can do::

globals()['x'] = 10

If you're inside a function, you probably want to look for another way
of doing what you're doing.

What's the actual task you're trying to accomplish here?

None. I asked just for curiosity. My problem has to do with the normal
case of a class or class instance. When I saw setattr/getattr as the way
to solve my problem I just felt curiosity on if and how it could be done
outside a class.

Thank you very much for your response.
Paulo
Apr 3 '07 #7
Paulo da Silva wrote:
Steven Bethard escreveu:
>Paulo da Silva wrote:
...
>If you're at the module level, you can do::

globals()['x'] = 10

If you're inside a function, you probably want to look for another way
of doing what you're doing.

What's the actual task you're trying to accomplish here?


None. I asked just for curiosity. My problem has to do with the normal
case of a class or class instance. When I saw setattr/getattr as the way
to solve my problem I just felt curiosity on if and how it could be done
outside a class.

Thank you very much for your response.
Paulo
You don't need setattr/getattr if you know in advance the name of the
attribute you need to access and you can get a reference to the object
whose attribute it is. So:
>>import sys
x = "Hello, Paulo"
sys.modules['__main__'].x
'Hello, Paulo'
>>globals()['x']
'Hello, Paulo'
>>>
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings http://holdenweb.blogspot.com

Apr 3 '07 #8
Steve Holden wrote:
You don't need setattr/getattr if you know in advance the name of the
attribute you need to access and you can get a reference to the object
whose attribute it is. So:
>>x = "Hello, Paulo"
>>import sys
>>sys.modules['__main__'].x
'Hello, Paulo'
a.k.a
>>import __main__
__main__.x
'Hello, Paulo'

STeVe
Apr 3 '07 #9
Steven Bethard wrote:
Steve Holden wrote:
>You don't need setattr/getattr if you know in advance the name of the
attribute you need to access and you can get a reference to the object
whose attribute it is. So:
> >>x = "Hello, Paulo"
import sys
sys.modules['__main__'].x
'Hello, Paulo'

a.k.a
>>import __main__
>>__main__.x
'Hello, Paulo'
Indeed. Any handle on the right object will do.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings http://holdenweb.blogspot.com

Apr 3 '07 #10

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

Similar topics

3
2722
by: Eric | last post by:
Slightly off topic, i know, but here goes: I'm trying to xlate a module of mine to C++. Only problem is, it makes heavy use of "setattr". Anyone know a straightforward way to do "setattr" in C++ ? thanks, Eric
8
1905
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
5
1365
by: szport | last post by:
There is an interesting skewness in python: class A(object): pass 17 But I can't write
4
3687
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
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
4297
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
1386
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)
8
7991
by: Gregor Horvath | last post by:
Hi, class A(object): test = "test" class B(object): a = A() In : B.a.test
4
10489
by: maestro | last post by:
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?
0
9699
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
10542
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...
0
10309
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10289
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
9119
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...
1
7600
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6840
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
5496
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...
1
4274
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.