getattr/setattr q.

Discussion in 'Python' started by Paulo da Silva, Apr 3, 2007.

  1. 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.
     
    Paulo da Silva, Apr 3, 2007
    #1
    1. Advertising

  2. Paulo da Silva wrote:
    > 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").


    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
     
    Steven Bethard, Apr 3, 2007
    #2
    1. Advertising

  3. Paulo da Silva

    Ben Finney Guest

    Paulo da Silva <> writes:

    > In a class C, I may do setattr(C,'x',10).


    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_module, '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
     
    Ben Finney, Apr 3, 2007
    #3
  4. Paulo da Silva

    7stud Guest

    On Apr 2, 10:08 pm, Paulo da Silva <> wrote:
    > Is it possible to use getattr/setattr for variables not inside
    > classes...?


    What does the python documentation say about the definition of
    setattr()?
     
    7stud, Apr 3, 2007
    #4
  5. On Tue, 03 Apr 2007 05:08:42 +0100, Paulo da Silva wrote:

    > 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").


    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
     
    Steven D'Aprano, Apr 3, 2007
    #5
  6. 7stud escreveu:
    > On Apr 2, 10:08 pm, Paulo da Silva <> wrote:
    >> 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
     
    Paulo da Silva, Apr 3, 2007
    #6
  7. 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
     
    Paulo da Silva, Apr 3, 2007
    #7
  8. Paulo da Silva

    Steve Holden Guest

    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
     
    Steve Holden, Apr 3, 2007
    #8
  9. 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
     
    Steven Bethard, Apr 3, 2007
    #9
  10. Paulo da Silva

    Steve Holden Guest

    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
     
    Steve Holden, Apr 3, 2007
    #10

  11. > Yes, but you shouldn't unless you really need to. You're better off
    > rethinking your algorithm.



    I need it but inside a class. The idea is to pass an instance of a class
    (think of something like a record but with some methods inside) with
    "fields", whose names are not known in advance, to another class that
    must handle those "fields" at the caller request given their names as
    parameter strings.

    Another use I am thinking of is in a xml driven program where some
    parameters "foo=bar", read as strings, must be converted into internal
    variables xxx_foo=bar. I have written a 1st draft using dicts but this
    way it is much easier and readable.


    Regards
    Paulo
     
    Paulo da Silva, Apr 3, 2007
    #11
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Nathan Harmston

    recursion error using setattr and getattr

    Nathan Harmston, Jun 7, 2007, in forum: Python
    Replies:
    0
    Views:
    289
    Nathan Harmston
    Jun 7, 2007
  2. Simon Brunning
    Replies:
    0
    Views:
    500
    Simon Brunning
    Jun 7, 2007
  3. Donn Ingle

    setattr getattr confusion

    Donn Ingle, Dec 8, 2007, in forum: Python
    Replies:
    7
    Views:
    292
    Donn Ingle
    Dec 8, 2007
  4. John Nagle
    Replies:
    4
    Views:
    1,320
    Carl Banks
    Mar 14, 2008
  5. maestro

    setattr and getattr, when to use?

    maestro, Aug 23, 2008, in forum: Python
    Replies:
    4
    Views:
    341
    Bruno Desthuilliers
    Aug 26, 2008
Loading...

Share This Page