4

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.

utengr
  • 3,225
  • 3
  • 29
  • 68
  • Personally I don't like to rename import with `as`. But sometimes it is required, for example if you want to import two objects with the same name into one namespace. – Klaus D. Oct 18 '17 at 09:19
  • 1
    Use your best judgement. If you have something that’s used extremely often, then making a short alias can help (for example, it’s common to `import sqlalchemy as sa` when working with SQLAlchemy), but if you have too many aliases, then they can get hard to remember. And someone reading for the first time will have to look them up. – Ry- Oct 18 '17 at 09:19
  • @KlausD. Yes, that's the usual use cases to avoid name clash. However, I am interested in using it for better readability which is kind of subjective though. – utengr Oct 18 '17 at 09:20
  • @Ryan I have very limited modules (2-5) usually so the alias will be limited too as I am importing modules than specific functions from them based in my use case. – utengr Oct 18 '17 at 09:21
  • 1
    There are technical reasons as to why you're able to import aliased, as already mentioned. i'm afraid anything regarding "better readability" might be subjective and can't be answered here – Felk Oct 18 '17 at 09:21
  • In my opinion , Cutting names off never improves code readability in most cases, somtimes when the names all look kinda same and hard to read you may do it like `import foobar1,foorbar2,foobar3` then it's good to import is `as` `bar1 , bar2 , bar3` – Ubdus Samad Oct 18 '17 at 09:22
  • 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). –  Oct 18 '17 at 09:25
  • @Evert can you elaborate this a bit further? couldn't really get it. – utengr Oct 18 '17 at 09:28
  • There is now one more "hidden" use case for the `import ... as ...` syntax, and it has to do with re-exporting names for type hinting validators (such as `mypy`); relevant [thread](https://stackoverflow.com/questions/72504576/why-use-from-module-import-a-as-a-instead-of-just-from-module-import-a/). However, this has the caveat where both names must be identical (i.e. `import process_words as process_words` to ensure `process_words` be a valid a re-export). – metatoaster Sep 14 '22 at 06:40

2 Answers2

5

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
  • are you referring to a use-case for import as? I assume you want to say this import as can be such in this specific situation for switching the actual import and similarly I can also use it for aliases in my use-case. If so then it would be nice if you can clarify it a bit in relationship to my question so I can accept it as an answer. – utengr Oct 18 '17 at 13:51
  • Another thing in python 2/3 is the urllib.parse etc. functions (they are the same but there location is different). I've also seen this with optional dependencies e.g. in the except block do `io = None`... not sure how I feel about it though. – Andy Hayden Oct 21 '17 at 05:33
3

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.

Andy Hayden
  • 359,921
  • 101
  • 625
  • 535