0

Python: 3.8.1

I am unable to append data in class variables using global() function.

class test():
    __cv__ = []

        def testglobalmethod(self, data):
            globals()['__cv__']=[data]
            print(__cv__)


    rrr = test()
    rrr.testglobalmethod("1")
    rrr.testglobalmethod("2")

Expected Results:- ['1','2']

Actual Results:- ['1'] ['2']

The append function produces below error:-

def testglobalmethod(self, data):
    globals()['__cv__'].append(data)
    print(__cv__)

Error: KeyError: '__cv__'

4
  • 1
    Why would you want to do that? Commented Feb 19, 2020 at 16:55
  • @wim I have learned the global() function recently. I tried with string and worked perfectly fine. So, I am trying with the list to see how it works. Commented Feb 19, 2020 at 16:56
  • 1
    __cv__ isn't global, it's a class attribute. Why do you expect to be able to access it via globals? Is it intentional that all your code is part of the test class scope? Commented Feb 19, 2020 at 16:57
  • 1
    Don't invent your own dunder names; they are reserved for use by the language itself. Just use cv, or _cv if you want to emphasize that it is for use by methods of the test class alone. Commented Feb 19, 2020 at 16:57

1 Answer 1

2

You have a class attribute, not a global variable.

class Test():
    __cv__ = []

    def testglobalmethod(self, data):
        Test.__cv__.append(data)
        print(Test.__cv__)


rrr = Test()
rrr.testglobalmethod("1")
rrr.testglobalmethod("2")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.