Note that there are some explanatory texts on larger screens.

plurals
  1. POImporting classes from different files in a subdirectory
    text
    copied!<p>Here's the structure I'm working with:</p> <pre><code>directory/ script.py subdir/ __init__.py myclass01.py myclass02.py </code></pre> <p>What I want to do is import in script.py the classes defined in <code>myclass01.py</code> and <code>myclass02.py</code>. If I do:</p> <pre><code>from subdir.myclass01 import * </code></pre> <p>It works fine for the class defined in <code>myclass01.py</code>. But with this solution if there are many classes defined in different files in <code>subdir</code> and I want to import all of them, I'd have to type one line for each file. There must be a shortcut for this. I tried:</p> <pre><code>from subdir.* import * </code></pre> <p>But it didn't work out.</p> <p><strong>EDIT</strong>: here are the contents of the files:</p> <p>This is <code>__init__.py</code> (using <code>__all__</code> as Apalala suggested):</p> <pre><code>__all__ = ['MyClass01','MyClass02'] </code></pre> <p>This is <code>myclass01.py</code>:</p> <pre><code>class MyClass01: def printsomething(): print 'hey' </code></pre> <p>This is <code>myclass02.py</code>:</p> <pre><code>class MyClass02: def printsomething(): print 'sup' </code></pre> <p>This is <code>script.py</code>:</p> <pre><code>from subdir import * MyClass01().printsomething() MyClass02().printsomething() </code></pre> <p>This is the traceback that I get when I try to run <code>script.py</code>:</p> <pre class="lang-none prettyprint-override"><code>File "script.py", line 1, in &lt;module&gt; from subdir import * AttributeError: 'module' object has no attribute 'MyClass01' </code></pre>
 

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