5

I am trying to determine some best practices of function imports and PEP 8 does not explicitly speak about this, in fact the PEP 8 imports section is relatively small. I was wondering what the best practices were when importing using abbreviations.

For example:

import pandas as pd
import numpy as np

Are easily understood because they are very widely used packages. For my own case, I may have some obscure classes or functions in a module that I wish to import like:

from my_module import my_fun_function as mff
...
myvar = mff(input1)

versus

from my_module import my_fun_function
...
myvar = my_fun_function(input1)

Is there a best practices reference on this?

d_kennetz
  • 5,219
  • 5
  • 21
  • 44
  • 1
    I did not downvote but I did close vote (primarily opinion-based). No, there is no "best practices reference" on this. I think your bounty will be refunded if a mod closes the question. – wim Apr 26 '19 at 03:27
  • Thanks for the explanation! Maybe you are right but I thought maybe there was a best practices for this. – d_kennetz Apr 26 '19 at 03:29
  • 1
    I don't think this question is opinion-based. The last sentence is "Is there a best practices reference on this?". The answer can be "No, there isn't" like [wim comment](https://stackoverflow.com/questions/55819364/python-imports-using-abbreviated-import-names#comment98381451_55819364). Or answer can be "Yes ... ... ... " – sanyassh Apr 26 '19 at 07:17
  • 2
    My personal *opinion* is that abbreviations are useful in the context of IPython / Jupyter (or other interactive shells), where someone is using these tools to explore a dataset. Abbreviations make repeated use easier, but make reading the code later on harder unless the abbreviation is widely adopted. – Martijn Pieters Apr 28 '19 at 08:13

3 Answers3

4

As you said. If the module is widely used it's acceptable to use abbreviations. If you have your custom module it is still okay to use abbrevation for it's name as long as it's well documented, clear and also widely used in code. Do not abbrevate if it's used just a couple of times.

However I would advise not to shorten function names as it feels like code obfuscation. I feel like ThisFunctionDoesThatThing(x) is way better than TFDTT(x).

mlotz
  • 130
  • 3
2

I think it depends on your audience. If your audience is familiar with the function you are abbreviating or if you providing documentation for the function, then it certainly can make code more readable. However, if you abbreviate every single obscure function you import (even if you only use it once), then it becomes significantly less readable and a pain to understand.

RoM
  • 52
  • 4
1

There are no standards, for the aliases, although some are well accepted.

Keeping the alias short looks good most of the time, but is not the only option.

prosti
  • 42,291
  • 14
  • 186
  • 151