Note that there are some explanatory texts on larger screens.

plurals
  1. POPythonize Me: how to manage caller context variables in Python? (Python/Django)
    primarykey
    data
    text
    <p>I'm trying to refactor a fairly hefty view function in Django. There are too many variables floating around and it's a huge function.</p> <p>Ideally, I want to modularize the view into logical functions. However, I have to pass the function context around to get easy access to the variables.</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>def complex_view(request, slug): some complex logic which creates variable abc ... ... some more complex logic which uses variable abc ... ... etc. </code></pre> <p>Should become something like:</p> <pre class="lang-py prettyprint-override"><code>def complex_view(request, slug): process_X() ...somehow pass variables and context to next function... process_Y() ... etc. def process_X(): ... def process Y(): ... </code></pre> <p>I can think of a few ways to do this, some of which were pointed out in this page: <a href="http://mail.python.org/pipermail/tutor/2009-February/067506.html" rel="nofollow noreferrer">http://mail.python.org/pipermail/tutor/2009-February/067506.html</a></p> <p><strong>a.</strong> Subfunctions defined in the master view. This seems kludgey since it's hard to tell which variables are shared and which aren't.</p> <p><strong>b.</strong> Passing <code>locals()</code> in as a dictionary. This is also kludgey because there are now two separate ways of accessing a variables: <code>xyz</code> and <code>contextDict['xyz']</code>. AND you have to use one in call <code>N</code>, and the next in call <code>N+1</code> on the stack.</p> <p><strong>c.</strong> Brute force pass in all variables to each function call and return relevant vars. This gets very tedious when there's a lot of vars involved.</p> <p><strong>d.</strong> In C++/C#, I would simply create a class <code>MyComplexViewContext</code>, define all the shared variables, and create member functions to carry out the work. Then you can use <code>self.xyz</code> for everything inside that class. I suppose I could use this method in Python as well. Not sure if this is the best way though.</p> <p>What's your take on the preferred way to do this in Python/Django?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload