I am wondering if we can use "import as
" for creating relatively compact or readable code. I am aware of its usual use cases based on PEP such as to void name clashes.
Here is the situation (keeping it very simple for the demonstration purpose). Let's say I have a module name, process_words.py.
process_words.py:
def word_to_lower(word):
return word.lower
process_article.py (lets the main script):
import process_words
word = "HELLO"
word_lower = process_words.word_to_lower(word)
print(word_lower)
Now would it be a bad or good practice to do something like this?:
import process_words as pw
word = "HELLO"
word_lower = pw.word_to_lower(word)
print(word_lower)
It's a very simplistic example. I have a couple of modules with each module having a couple of functions. Importing each function with from module import something
isn't an option. To me, it feels like, if I use import as with some shortcut names, it will improve the code readability. Any thoughts?
NOTE: I am referring to custom modules here.
Generally this should be avoided as much as possible.
However it is used to great effect when the import name is ubiquitous, for example numpy is always np
, pandas is always pd
. You shouldn't have to look up the name, you sit in front of an unseen code base: you see np.array
you know what's going on. Although it's only slightly shorter, it can be skipped over much more easily.
Another time where it may be useful is in a single module which uses another module everywhere, every few lines or ten lines is a call-out to this module. Then I would consider using an as import to cut down the size (for reading) of the file.
I've done this before with a flask app that was a very thin wrapper around a (testable) module.
If it's an internal API only (and the meaning is completely clear from the context), then perhaps it makes sense to name it pw.py
rather than process_words.py
. IMO it's a little on the short side, but words.py
might work well (however "process" is a bit of a generic word, so I might look foor a more specific verb...).
Context is important, as a submodule of words
, it might make sense to call it funcs
for example.
One practical issue is where you start changing libraries or modules used, and where you can switch the actual import without changing the code: import somemodule
would become import newmodule as somemodule
.
It's something I do within a try-except block when having Python 2/3 compatibility code (I guess a package like six
has quite a bit of this). For example:
try:
# Are we using Python 2?
import StringIO as io
except ImportError:
# No, we're using Python 3 instead
import io