Python - how to clear class variables automatically when class variables are resource - python

I have a problem with dealing with class variables in Python. I have a code as the following.
class TempClass:
resource = xlwings.Book() # xlwings is a library manipulating Excel file.
#...
Here, to clear 'resource', I need to execute
resource.close()
Is there any built-in function called when a class (not object) is cleared, so that I can write the above code in that function? Or is there any way to clear 'resource'?
My Python version is 3.6

Don't use a class variable. A class variable is alive as long as the class exists probably as long as your python interpreter isn't shutdown.
Normally with ressources that need to be closed you can simply use a contextmanager (for example contextlib.closing):
import contextlib
# I don't have xlwings so I create some class that acts like it:
class Book(object):
def __init__(self):
print('init')
def close(self):
print('close')
The actual "context" can be created and used like this. Inside the block the resource is alive and it's closed after the block ends. I use prints to show where each method is called:
print('before the context')
with contextlib.closing(Book()):
print('inside the context')
print('after the context')
Which prints:
before the context
init
inside the context
close
after the context

Related

Global or static function in python classes?

I've got a class that manages a video camera and file stream. Each instance of the class is a frame that has a bunch of methods, attributes, etc. I'm doing all the initialization outside a function so it happens once and sets a few variables that are global to all instances of the class. Those global variables include Video and File objects that i need to close properly at shutdown from my main program.
I'm newish to Python and mostly Java/C/C++ background and I remember having functions that were associated with the class that i could call that accessed global (static) class variables. Can i do something similar in Python?
Here is my pseudo code for my class:
class MyClass:
global_variable = 1
openFile = file.open()
def someMethod( self ):
do stuff
def cleanUpStuff():
self.openFile.release()
Now in my main program I need to call cleanUpStuff() to close out my camera and files properly. I'm creating hundreds of instances of MyClass objects that I use and get destroyed by the garbage collection at some point. So i need a way to call at the Class level.
while True:
a = MyClass()
a.someMethod()
if something:
break
MyClass.cleanUpStuff()
Thanks to John this appears to work exactly like i want. I didn't know about "decorators" so i have no idea why this works exactly but that is a path i can follow now at least i've solved this problem...
#classmethod
def cleanUpStuff( MyClass ):
MyClass.openFile.release()

Is there a magic method to know that a base class is used through inheritance?

I'd like to describe my problem with code to make it clear:
class MyBaseClass(object):
def __init__(self):
print 'foobar'
def __call__(self):
print 'spameggs'
def __is_used__(self): # This is only a pseudo method
print 'I\'m being used! - MyBaseClass'
class MySubClass(MyBaseClass):
def __init__(self):
print 'monty python'
Now I'd like to know if there is a similar magic method __is_used__ for a class object to know if it is being use as a parent/base class of another class (sub)?
Example usage:
class_a = MySubClass()
# Output
# monty python
# I'm being used! - MyBaseClass
Use Case
To avoid confusion (I apologize). A best example would be a mixin. Example an S3Mixin.
An S3Mixin has a capabilities to upload and download file to S3 buckets.
class S3Mixin(object):
def upload(self):
def download(self):
Now i want to use it to ImageFile and VideoFile classes.
class ImageFile(S3Mixin):
# omitted lengthy properties
class VideoFile(S3Mixin):
# omitted lengthy properties
Now each object has a function to use the s3 basic functionalities. Now the real problem arise when I try to use another module inside a S3Mixin which cause a circular dependency issue. Now to avoid it I have to import it inside each function of S3Mixin. I tried putting it on the __init__ method and __call__ method which is obviously not going to work.
I don't want to do that. Instead I wanted to know if there is available method so I can import all the conflicted module preferable on a magic method of an S3Mixin.
Note:
I'm not asking for a checking of a class that is a subclass of another class. That is far from the question. I would like to know if there is a MAGIC METHOD so i can further create a logic in it when a base class is used.

How to inherit Class attributes Python

I use RaspberryPi3 with Python to Remote control GPIO of other RPIs.
I created a class to initialize connections and pin for all Pis:
class relay(pigpio.pi):
def __init__(self,ip_addr):
pigpio.pi.__init__(self)
self.GPIO=[4,5,6,12]
self.rpi=pigpio.pi(ip_addr)
for t in range(len(self.GPIO)):
self.rpi.write(self.GPIO[t],0)
def switch_state(self,i,state):
self.rpi.write(self.GPIO[i],state)
pi_1=relay('192.168.2.112') # creating first Rpi link
pi_2=relay('192.168.2.113') # creating second Rpi link
x=0
pi_1.switch_state(x,0)
how can I inherit pigpio module's attributes into relay ? in order not to create switch_state as I did, but to use read, write and more that belong to pigpio
If I'm right you want to extend a module to a class by inheritance.
If that is true, you can not perform that without hacky things but anyway, you should not do that.
Module and classes are not designed to be used in that way.
You better keep using module's functions as expected, I see no good reasons to map module's function within a class.
You could just map it by hand like:
import spam
class Foo():
def egg(self, *args, **kwargs):
return spam.egg(*args, **kwargs)
But again, I'm not sure there is a valid reason to do that - but there is plenty of valid reasons to not..

Python 3 unit-testing, create mock of singleton class function

I'm working on creating unittests for my project.
I have a class called TimerHandler that needs to be tested. This class uses a class called AudioHandler. Both of these classes are singletons. see code below.
timer_handler.py
class TimerHandler(metaclass=Singleton):
def play(self):
# some code that needs to be tested
AudioHandler().start()
audio_handler.py
class AudioHandler(metaclass=Singleton):
def start(self):
# some code that connects with an audio device
I'm trying to mock the start method of AudioHandler so it will just return None and won't try to connect to an audio device. The unittest looks like this:
#patch.object(AudioHandler, 'start', return_value=None)
def test_play_pause(self, start):
self.timer_handler.play()
The problem is that it is still running the code in the original start function in AudioHandler.
How can I write a test function that removes/mocks the functionality of the start function in AudioHandler?
Thanks in advance
You should mock a class from a module path where you are importing it
#patch('timer_handler.AudioHandler')
And after that, you can add your method to the mock object
Please read
https://docs.python.org/3/library/unittest.mock.html#where-to-patch

python: How do I dynamically create bound methods from user supplied source code?

I would like to construct a class in python that supports dynamic updating of methods from user supplied source code.
Instances of class Agent have a method go. At the time an instance is constructed, its .go() method does nothing. For example, if we do a=Agent(), and then a.go() we should get a NotImplementedError or something like that. The user then should be able to interactively define a.go() by supplying source code. A simple source code example would be
mySourceString = "print('I learned how to go!')"
which would be injected into a like this
a.update(mySourceString)
Further invokations of a.go() would then result in "I learned how to go!" being printed to the screen.
I have partially figured out how to do this with the following code:
import types
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class NotImplementedError(Error):
pass
class Agent(object):
def go(self):
raise NotImplementedError()
def update(self,codeString):
#Indent each line of user supplied code
codeString = codeString.replace('\n','\n ')
#Turn code into a function called func
exec "def func(self):\n"+' '+codeString
#Make func a bound method on this instance
self.go = types.MethodType(func, self)
QUESTIONS
Is this implementation sensible?
Will this implementation incur unexpected scope issues?
Is there an obvious way to sandbox the user supplied code to prevent it from touching external objects? I can think of ways to do this by supplying sets of allowed external objects, but this seems not pythonic.
Possibly useful SO posts
What's the difference between eval, exec, and compile in Python?
Adding a Method to an Existing Object
(I am working in python 2.6)

Categories

Resources