Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Globals are rarely a good idea.</p> <p>Implicit variables are rarely a good idea.</p> <p>An implicitly-used global is easy to indict as also "rarely good".</p> <p>Additionally, you don't want <code>A.__init__()</code> doing anything "class-level" like updating some mysterious collection that exists for the class as a whole. That's often a bad idea. </p> <p>Rather than mess with implicit class-level collection, you want a <strong>Factory</strong> in <code>module_a</code> that (1) creates <code>A</code> or <code>B</code> instances and (b) updates an explicit collection.</p> <p>You can then use this factory in <code>module_b</code>, except with a different collection.</p> <p>This can promote testability by exposing an implicit dependency.</p> <p>module_a.py</p> <pre><code>class Factory( object ): def __init__( self, collection ): self.collection= collection def make( self, name, *args, **kw ): obj= eval( name )( *args, **kw ) self.collection.append( obj ) return obj module_collection = [] factory= Factory( module_collection ) </code></pre> <p>module_b.py</p> <pre><code>module_collection = [] factory = module_a.Factory( module_collection ) </code></pre> <p>Now a client can do this</p> <pre><code>import module_b a = module_b.factory.make( "A" ) b = module_b.factory.make( "B" ) print( module_b.module_collection ) </code></pre> <p>You can make the API a bit more fluent by making the factory "callable" (implementing <code>__call__</code> instead of <code>make</code>.</p> <p>The point is to make the collection <em>explicit</em> via a factory class.</p>
 

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