From d330ad1b40242e4d78289a5595fa70c158c07e6c Mon Sep 17 00:00:00 2001 From: Robin Dunn Date: Mon, 29 Jan 2018 12:23:57 -0800 Subject: [PATCH] Add context manager methods to wx.DC --- CHANGES.rst | 6 ++++++ etg/dc.py | 4 ++++ unittests/test_dc.py | 12 ++++++++++++ 3 files changed, 22 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 12197b12..1c6291bb 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -210,6 +210,12 @@ Changes in this release include the following: point values to integers, and a couple other possible incorrect conversions. (#536) +* Added context manager methods to wx.DC that explicitly destroys the C++ + part of the DC upon exit. Using DCs as context managers is not required, but + can be handy in the rare cases where something holds on to a DC for too + long, perhaps unintentionally. (#680) + + diff --git a/etg/dc.py b/etg/dc.py index a62c481b..d320d9ee 100644 --- a/etg/dc.py +++ b/etg/dc.py @@ -264,6 +264,10 @@ def run(): c.addPyCode('DC.GetCGContext = wx.deprecated(DC.GetCGContext, "Use GetHandle instead.")') c.addPyCode('DC.GetGdkDrawable = wx.deprecated(DC.GetGdkDrawable, "Use GetHandle instead.")') + # context manager methods + c.addPyMethod('__enter__', '(self)', 'return self') + c.addPyMethod('__exit__', '(self, exc_type, exc_val, exc_tb)', 'self.Destroy()') + # This file contains implementations of functions for quickly drawing # lists of items on the DC. They are called from the CppMethods defined diff --git a/unittests/test_dc.py b/unittests/test_dc.py index c38c1fec..466e6841 100644 --- a/unittests/test_dc.py +++ b/unittests/test_dc.py @@ -175,6 +175,18 @@ class dc_Tests(wtc.WidgetTestCase): dc.DrawLines( [(15,15), (35,15), (35,35), (35,15), (15,15)] ) + def test_dcContextManager(self): + import wx.siplib + with wx.ClientDC(self.frame) as dc: + dc.DrawLine(0,0,100,100) + + # check ownership + assert wx.siplib.ispyowned(dc) + + # check the DC's ownership has changed + assert not wx.siplib.ispyowned(dc) + + #---------------------------------------------------------------------------