-1

What is the best way to append and clear the list deriv_position = [] from inside the function test?

I got NameError: name 'deriv_position' is not defined

class TestClass:

    deriv_position = []

    def test():
        if len(deriv_position) > 0:
            print("trade is open")
            deriv_position.clear()
        else:
            print("trade is close")
            deriv_position.append("1")


    test()    
siad
  • 1
  • 2
  • It's not a global variable, it's a class variable. Use `test.deriv_position` – Barmar Sep 29 '21 at 17:39
  • 2
    Naming both the class and method `test` isn't helping. And it's unclear why that's in a class at all, if you're going to call the method immediately inside the class definition. – jonrsharpe Sep 29 '21 at 17:41
  • 1
    A `class` statement does not establish a new scope, but neither do assignments in a class statement modify the enclosing scope. The *namespace* created by a class statement is outside the hierarchy of scopes in Python. – chepner Sep 29 '21 at 17:46
  • @chepner Really? Classes don't establish a new scope? This could be why a recent project is losing its objects after I reinstate Class attributes. – Xammax Sep 29 '21 at 17:58

1 Answers1

0

In python, you refer to class variables using the self keyword. So inside the function, you can pass in self and then use it...

class TestClass:

    def __init__(self):
        self.deriv_position = []

    def test(self):
        if len(self.deriv_position) > 0:
            print("trade is open")
            self.deriv_position.clear()
        else:
            print("trade is close")
            self.deriv_position.append("1")


TestClass().test()

You may find it worthwhile to read up on how classes work in Python: https://docs.python.org/3/tutorial/classes.html#a-first-look-at-classes

Alternatively, if you are not using the class as a class (in your example, you are not), then there is no need for it. Just declare a global variable at the top of the file, and the test function just a function in the file.

MaMaG
  • 359
  • 1
  • 9
  • " you refer to class variables using the self keyword" - well, this needs a big warning though. It works here as long as you only mutate the class variable. Anything like `self.deriv_position = ` run in any method would create an instance variable with the same name that would shadow your class variable further on. It would be much safer to refer to it through the class, not the instance. See for example https://stackoverflow.com/a/25577642/550094 for more details. – Thierry Lathuille Sep 29 '21 at 17:58
  • that's exactly what I'm looking for thanks – siad Sep 29 '21 at 18:02
  • @ThierryLathuille that's a good point. I'll edit to make it a true instance variable. – MaMaG Sep 29 '21 at 18:06