Joe Healey
Joe Healey

Reputation: 1252

import another module or implement an existing call

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.

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'?

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 glob.glob() 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).

headers = []
with open(hhresult_file) as result_fasta:
    for line in result_fasta:
        if line.startswith(">"):
            line = line.split("_")[0]
            headers.append(line.replace(">",""))

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

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?

Upvotes: 0

Views: 23

Answers (1)

Vasili Syrakis
Vasili Syrakis

Reputation: 9631

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

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.

There are certainly considerations to be made when making additional imports, mostly when they are not part of the Python standard library.
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.

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.

It's a continual consideration that has to be made.

Upvotes: 1

Related Questions