-1

Why are packages like glob and psycopg2 not shortened on import? Is there any other reason than convention or personal preference? Perhaps best practice?


Example: For the sake of readability and reducing the overhead of loading an entire package:

# Best practice
from sklearn.metrics import r2_score
model_score = r2_score(arg1, arg2)

# Similarly, to keep names short
import sklearn
model_score = sklearn.metrics.r2_score(arg1, arg2)

Similarl example: long package names are just shortened, especially if many part of the package are used

# Best practice
import pandas as pd
import numpy as np
import seaboard as sns
import matplotlib.pyplot as plt

df = pd.DataFrame(dictobject)
w_avg = np.average(mylist, weights=w)
sns.heatmap(df)
plt.show()

# instead of
import pandas
import numpy
import seaboard
import matplotlib

df = pandas.DataFrame(dictobject)
w_avg = numpy.average(mylist, weights=w)
seaborn.heatmap(df)
matplotlib.pyplot.show()

Why do we not do the same with glob?

# Shouldn't this be best practice?
import glob.glob as gl
jpgs = gl('path/*.jpg')

# But instead this seems more prominent:
import glob
jpgs = glob.glob('path/*.jpg')

Perhaps in case if we needed one of glob.glob's lesser know cousins (glob.iglob or glob.escape), we could import glob as gl (and then use gl.iglob or gl.escape).

This question: python import module vs import module as, did not answer my question.

DannyDannyDanny
  • 838
  • 9
  • 26
  • 1
    `"Is there any other reason than convention or personal preference?"` No, which is why I voted to close this question as "opinion-based" – DeepSpace Jul 22 '20 at 13:03
  • It's not that some modules are shortened while others are not. Modules such as `glob` simply define a class with the same name as the module. So `glob.glob` means, inside package `glob` access class `glob`, similar to how `pandas.DataFrame` means inside module `pandas` access class `DataFrame`. Everything else is based on preference or what module methods and structures you need access to. – h0r53 Jul 22 '20 at 13:07
  • 1
    @h0r53 that is not what OP is asking. They ask why it is a "convention" to see `import pandas as pd` but not `import glob as g` – DeepSpace Jul 22 '20 at 13:09
  • Then yes, this is opinion based and not well suited here – h0r53 Jul 22 '20 at 13:16
  • 1
    Thanks for your input. My question is **"Are there reasons for doing X?"** and the objective answer seems to be: **"No, it's purely convention and personal preference"**. I dont believe it is opinion based. – DannyDannyDanny Jul 22 '20 at 13:21
  • So you don't "believed" the answer just because it doesn't fit with what you thought is the "real" answer? then why bother asking at all? – DeepSpace Jul 22 '20 at 14:01
  • See the accepted answer. That is all I was looking for. Thank you for your help. – DannyDannyDanny Jul 23 '20 at 10:59

1 Answers1

1

No, it's purely convention and personal preference

Luke Storry
  • 6,032
  • 1
  • 9
  • 22