Dynamic variable optimization

This is the place for queries that don't fit in any of the other categories.

Dynamic variable optimization

Postby weatherman » Fri Jan 31, 2014 1:49 pm

What is the best way to accomplish the following dynamic variable assignment without using exec()?

Code: Select all
namecount=0
for names in wwa_names[1].splitlines():
       if names:
            namearr = names.split("...")
            exec("%s = namearr[1]" % (self._authorstorage[namecount]))
            namecount = namecount + 1


Thanks! Would most appreciate an explanation w/code.
weatherman
 
Posts: 9
Joined: Sat Jan 18, 2014 7:29 pm

Re: Dynamic variable optimization

Postby metulburr » Fri Jan 31, 2014 1:58 pm

http://docs.python.org/2/library/functions.html#setattr

Code: Select all
class Klass:
    def __init__(self):
        pass
       
obj = Klass()
setattr(obj, 'bar', 'foo')
print(obj.bar)
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1365
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Dynamic variable optimization

Postby Mekire » Fri Jan 31, 2014 2:35 pm

Agreed; setattr and getattr can be very useful when used responsibly.

You also might want to look into something as simple as kwargs:
Code: Select all
class A(object):
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

Code: Select all
>>> name_dict = {"this" : 2, "that" : 3, "the_other" : 4}
>>> a = A(**name_dict)
>>> a.this
2
>>> a.that
3
>>> a.the_other
4

-Mek
User avatar
Mekire
 
Posts: 986
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Dynamic variable optimization

Postby weatherman » Fri Jan 31, 2014 3:54 pm

Awesome! Thank you!
weatherman
 
Posts: 9
Joined: Sat Jan 18, 2014 7:29 pm


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 2 guests