0

I am trying to create a function that will create a new object of a class through exec every time called, but I could not access the object.

Here is a piece of example code:

a.py:

class test(object):
    def __init__(self):
        self.var='vari'
def testfunc():
    exec("""aaa=test()
aaa.var='varia'""")

b.py:

import a
a.testfunc()
print(a.aaa.var)

When running b.py, it returns the following:

Traceback (most recent call last): File "C:\Users\lenovo\Desktop\pythontest\b.py", line 3, in print(a.aaa.var) AttributeError: module 'a' has no attribute 'aaa'

Why is this?

John Hao
  • 39
  • 7
  • is testfunc() within the test class or outside the class? – Bibek Bhandari Jun 16 '18 at 11:35
  • It is outside the class definition. – John Hao Jun 16 '18 at 11:37
  • What do you mean by execution context? Do you mean that there is a scope problem and that there is a b.aaa.var but not an a.aaa.var? Or does that mean that the object is only accessible from inside the scope of the function? – John Hao Jun 16 '18 at 11:51
  • @Take_Care_ I don't know what you mean by "execution context", but everything else about your comment is incorrect. This has nothing to do with modules and imports. It's a simple matter of `aaa` being a local variable and not a global one. – Aran-Fey Jun 16 '18 at 12:13
  • `aaa=test()` creates a local variable. If you want to access that variable from another module as `a.aaa`, you have to make it a global variable. This would've been an obvious mistake if you hadn't used `exec`, so keep in mind that `exec` is 1) dangerous and 2) bad for your code's readability. There are better ways to define global variables. – Aran-Fey Jun 16 '18 at 12:16
  • @Aran-Fey You got a point there. I certainly agree with you on everything, but not the comment about exec(). It is not dangerous if it is not coupled by the user's input, and most of my execs do not. They are merely for references, as in: aaa='aaa' exec(aaa+' = test()) – John Hao Jun 16 '18 at 12:41
  • If it's something that simple, you don't even need `exec` at all. *If* you need `exec`, it's almost always dangerous. – Aran-Fey Jun 16 '18 at 13:00

1 Answers1

0

I looked at Take_Care_'s comment, then tested it out. If I globalize aaa before assigning it to an object of test, I could access it from b.py.

John Hao
  • 39
  • 7