0
class Duck():
    def __init__(self):
        print("complex operation oink oink !!!")

duck = Duck()
duck = None

I suppose that it's a very bad idea but... why ? like i do this a lot of time and it seems to do the work evey time so I'm wondering, is this just purist theorical biase or is this really dangerous and if yes, in which case and how to detect it ? (You can answer yes or no to the title if you feel that the question is too long ^^, or give a link to understand well if the answer is too long)

Thank you in advance

Utopion
  • 935
  • 1
  • 4
  • 15
  • 2
    You should prefer to write small functions, through which variables naturally go out of scope soon when the function ends, making this topic somewhat moot… – deceze Jun 22 '21 at 13:07
  • 2
    One of the big selling points of Python is that we *don't* think about this. If you're in an environment where you care how memory is allocated, you should be using C or Rust, not a high-level language like Python. – Silvio Mayolo Jun 22 '21 at 13:08
  • 1
    It depends on what implementation of Python you are using. CPython uses reference counting. When you write `duck = None`, the reference count of the `Duck` instance is decremented. If the reference count drops to 0, the memory is freed. A different implementation might use garbage collection, in which case the `Duck` instance would be *eligble* for garbage collection, but you don't necessarily know when that will happen. – chepner Jun 22 '21 at 13:26
  • 2
    Consider using `del duck` instead. It also decrements the reference counter for whatever whatever is referencing `Duck()` from the previous line. And instead of getting `'NoneType' object has no attribute 'quack'` later in your code when you do `duck.quack()` after you've set it to `None`, with `del` you'd get `name 'duck' is not defined`. And if you're using an IDE which supports it, you'd get a warning/error while coding, telling you that the variable is not defined. Better to have no variable defined than 10 variables pointing to `None`. Easier to debug related/unrelated errors that occur. – aneroid Jun 22 '21 at 13:34

0 Answers0