Skip to content Skip to sidebar Skip to footer

Use Case For "import As" In Python

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

Solution 1:

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 alwaysnp, pandas is alwayspd. 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.

Post a Comment for "Use Case For "import As" In Python"