Carbon
Carbon

Reputation: 3943

Can I create a constructable SimpleNamespace in Python?

I'm trying to construct an twoNum dynamically - I've got the constants built, and the lambda works, but I'm not sure how to make ns constructible.

class twoNum:
    a = 1
    b = 2

    def c(self):
        return self.a + self.b


ns = types.SimpleNamespace()
setattr(ns,'a',1)
setattr(ns,'b',2)
setattr(ns,'c',lambda : self.a + self.b)

When I do:

r = ns()

I get:

TypeError: 'types.SimpleNamespace' object is not callable

Upvotes: 0

Views: 1261

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

You have to instantiate ns outside the python script you defined it on. So if your script.py has the following code in it

import types

class twoNum:
    a = 1
    b = 2

    def c(self):
        return self.a + self.b


ns = types.SimpleNamespace()
setattr(ns,'a',1)
setattr(ns,'b',2)
setattr(ns,'c',lambda : self.a + self.b)

Then the following will work .

In [1]: from script import ns                                                                                                                                                                                                                 

In [2]: ns                                                                                                                                                                                                                                    
Out[2]: namespace(a=1, b=2, c=<function <lambda> at 0x110dde6a8>)

In [3]: ns.a                                                                                                                                                                                                                                  
Out[3]: 1

In [4]: ns.b                                                                                                                                                                                                                                  
Out[4]: 2

Also your definition of function c is incorrect, you don't have a and b as class attributes, so you cannot do self.a or self.b, you can try as follows

def c(self):
    return a + b

Which can then be run as follows

In [5]: ns.c(5,6)                                                                                                                                                                                                                             
Out[5]: 11

Upvotes: 1

Related Questions