-1

I want to write a function that sets a self variable to None, but it feels very wrong to write a million functions for each variable.

I want to do something like:

class MyClass():
   def __init__(self):
       self.duck = None
       self.dog = None
   def makeduck(self):
       self.duck = "Duck"
   def makedog(self):
       self.dog = "Dog"
   def deleteVar(self,var):
       self.var = None # or del self.var

I want to do this because the variables tend to be very large and I don't want to overload my ram so I have to delete some not needed vars depending on the context.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Typ
  • 13
  • 5
  • 1
    Do you know how much space a string consumes, do you how much ram you have?? Don't optimize prematurely. I doubt you have a million variables and even if that still would not be a problem other than bad design. – luk2302 Nov 19 '21 at 19:34
  • 1
    In general, if you're _that_ memory-constrained, Python is the wrong language. Anyhow, what's your actual specific technical question? – Charles Duffy Nov 19 '21 at 19:34
  • ...in general, it would make a separate class for each type so you can use `__slots__` if you're serious about constraining memory usage. See [Usage of `__slots__`?](https://stackoverflow.com/questions/472000/usage-of-slots) – Charles Duffy Nov 19 '21 at 19:36
  • 1
    Why? Why do you need a method for this at all? Note, it doesn't *delete* anything – juanpa.arrivillaga Nov 19 '21 at 19:36
  • Why is it important why i need it for? If i explain my whole project it would massively miss the point of a concise question. – Typ Nov 20 '21 at 13:08

1 Answers1

0

It is indeed possible.

Although having a clear separation between what should be program structure: variables, and data: text inside strings, Python allows one to retrieve and operate on variables or attributes given their name.

In this case, you will want to use the setattr and delattrcalls: both take an instance, an attribute name, given as textual data (a string), and operate on them like the corresponding assignment (self.var = xxx) and deleting (del self.var ). statements (but, as you intend to use, with "var" being a variable containign the actual attribute name).

def deleteVar(self, var):
    # setattr(self, var, None). #<- sets attribute to None
    delattr(self, var). # <- deletes attribute.
  

(for completeness: there is also the getattr call which allows attribute retrieval on the same bases)

That said: the memory usage of hard-coded variables, even if you have tens of them, will likely be negligible in a Python process. Having tens of different "deleter" methods, however, would indeed be clumsy, and there are situations were your code might be more elegant by passing your attributes as data, as you intent.

jsbueno
  • 99,910
  • 10
  • 151
  • 209