Python classes - run method when any other method is called
<p>I am writing a Python app which will use a config file, so I am delegating the control of the config file to a dedicated module, <code>configmanager</code>, and within it a class, <code>ConfigManager</code>.</p>

<p>Whenever a method within <code>ConfigManager</code> is run, which will change my config file in some way, I will need to get the latest version of the file from the disk. Of course, in the spirit of DRY, I should delegate the opening of the config file to it's own function.</p>

<p>However, I feel as though explicitly calling a method to get and return the config file in each function that edits it is not very "clean".</p>

<p>Is there a recommended way in Python to run a method, and make a value available to other methods in a class, whenever and <em>before</em> a method is run in that class?</p>

<p>In other words:</p>

<ul>
<li><p>I create <code>ConfigManager.edit_config()</code>.</p></li>
<li><p>Whenever <code>ConfigManager.edit_config()</code> is called, another function <code>ConfigManager.get_config_file()</code> is run.</p></li>
<li><p><code>ConfigManager.get_config_file()</code> makes a value available to the method <code>ConfigManager.edit_config()</code>.</p></li>
<li><p>And <code>ConfigManager.edit_config()</code> now runs, having access to the value given by <code>ConfigManager.get_config_file()</code>.</p></li>
</ul>

<p>I expect to have many versions of <code>edit_config()</code> methods in <code>ConfigManager</code>, hence the desire to DRY my code.</p>

<p>Is there a recommended way of accomplishing something like this? Or should I just create a function to get the config fine, and manually call it each time?</p>

<p>Since you get something from disk, you open a file. So, you could use the class with the <code>with</code> "function" of python. </p>

<p>You should check the context managers. With that, you will be able to implement the functionality that you want each time that someone access the config file through the <code>__enter__</code> method and (if it is needed) implement the functionality for stop using the resource with the <code>__exit__</code> method. </p>

python