import another module or implement an existing call
<p>This may be a subjective question so I understand if it gets shut down, but this is something I've been wondering about ever since I started to learn python in a more serious way.</p>

<p>Is there a generally accepted 'best practice' about whether importing an additional module to accomplish a task more cleanly is better than avoiding the call and 'working around it'?</p>

<p>For example, I had some feedback on a script I worked on recently, and the suggestion was that I could have replaced the code below with a <code>glob.glob()</code> call. I avoided this at the time, because it meant adding another import that seemed unecessary to me (and the actual flow of filtering the lines just meshed with my thought process for the task).</p>

<pre><code>headers = []
with open(hhresult_file) as result_fasta:
    for line in result_fasta:
        if line.startswith("&gt;"):
            line = line.split("_")[0]
            headers.append(line.replace("&gt;",""))
</code></pre>

<p>Similarly, I decided to use an <code>os.rename()</code> call later in the script for moving some files rather than import <code>shutil</code>.</p>

<p>Is there a right answer here? Are there any overheads associated with calling additional modules and creating more dependencies (lets say for instance, that the module wasn't a built-in python module) vs. writing a slightly 'messier' code using modules that are already in your script?</p>

<p>This is quite a broad question, but I'll try to answer it succinctly.</p>

<p>There is no real best practice, however, it is generally a good idea to recycle code that's already been written by others. If you find a bug in the imported code, it's more beneficial than finding one in your own code because you can submit a ticket to the author and have it fixed for potentially a large group of people.</p>

<p>There are certainly considerations to be made when making additional imports, mostly when they are not part of the Python standard library.<br>
Sometimes adding in a package that is a little bit too 'magical' makes code harder to understand, because it's another library or file that somebody has to look up to understand what is going on, versus just a few lines that might not be as sophisticated as the third party library, but get the job done regardless.</p>

<p>If you can get away with not making additional imports, you probably should, but if it would save you substantial amounts of time and headache, it's probably worth importing something that has been pre-written to deal with the problem you're facing.</p>

<p>It's a continual consideration that has to be made.</p>

python