user517893
user517893

Reputation: 471

Python: how can I import the namespace of some object to current namespace?

I have a Python class, which contains several nested parameter groups:

class MyClass(object):
    #some code to set parameters

    def some_function(self):
        print self.big_parameter_group.small_parameter_group.param_1
        print self.big_parameter_group.small_parameter_group.param_2
        print self.big_parameter_group.small_parameter_group.param_3

I want to reduce code needed to access parameters. What should I place at the top of some_function to access the parameters simply by their names (param_1, param_2, param_3)? And what should I place somewhere in MyClass to apply this shortcut for all its methods, not only some_function?

Upvotes: 2

Views: 170

Answers (3)

David Ly
David Ly

Reputation: 31586

One way is to create properties for each of them:

@property
def param_1(self):
    return self.big_parameter_group.small_parameter_group.param_1
@property
def param_2(self):
    return self.big_parameter_group.small_parameter_group.param_2
@property
def param_2(self):
    return self.big_parameter_group.small_parameter_group.param_2

Another more robust but less explicit way would be to override the getattr method like so:

def __getattr__(self, name):
    import re
    p = re.compile('param_[0-9]+')
    if p.match(name):
        return getattr(self.big_parameter_group.small_parameter_group, name)
    else:
        return super(MyClass, self).__getattr__(name)

This will work for any property that matches the format specified by the regex (param_[some number])

Both of these methods will allow you to call self.param_1 etc, but it's just for retriving. If you want to set the attributes you'll need to also create a setter:

@param_1.setter
    def param_1(self, value): 
        print 'called setter'
        self.big_parameter_group.small_parameter_group.param_1 = value

Or to complement getattr:

def __setattr__(self, name, value):
    import re
    p = re.compile('param_[0-9]+')
    if p.match(name):
        return setattr(self.big_parameter_group.small_parameter_group, name, value)
    else:
        return super(MyClass, self).__setattr__(name, value)

(Haven't tested these out so there may be typos but the concept should work)

Upvotes: 2

Brandon Rhodes
Brandon Rhodes

Reputation: 89375

I would start the function with

spg = self.big_parameter_group.small_parameter_group

and then use that abbreviation. You could define abbreviations like this in __init__(), I suppose, if you wanted to use them everywhere with self on the front.

Upvotes: 6

Jakob Bowyer
Jakob Bowyer

Reputation: 34688

Inside your init you could always do.

self.local_param_1 = self.big_parameter_group.small_parameter_group.param_1

Upvotes: 1

Related Questions