-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()    
4
  • It's not a global variable, it's a class variable. Use test.deriv_position Commented Sep 29, 2021 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. Commented Sep 29, 2021 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. Commented Sep 29, 2021 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. Commented Sep 29, 2021 at 17:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

" 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 = <whatever> 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 stackoverflow.com/a/25577642/550094 for more details.
that's exactly what I'm looking for thanks
@ThierryLathuille that's a good point. I'll edit to make it a true instance variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.