1

I'm new to python and I've been seeing import x as _x. I would like to know how this is different from import x. Thanks!

  • The `as` keyword is used to create an alias. When you use `import x as y` you are using `y` to access `x`'s properties and methods instead of x. Could be useful if the module name is too long, like this, `import pandas as pd`. – Tharu Jan 31 '22 at 06:22
  • Both are same. Here _x is is an alias of x. Its useful when the module you want to import has a very lengthy name. – AJITH Jan 31 '22 at 06:22
  • Related: https://stackoverflow.com/q/22245711/4046632 and https://stackoverflow.com/q/710551/4046632 – buran Jan 31 '22 at 06:23
  • The difference is simply the name which you can use to refer to the module. `import name` makes it available as `name`, `import name as other_name` makes the same `name` available as `other_name` (and not as `name`) – Grismar Jan 31 '22 at 06:26

2 Answers2

2

As a non-native mediocre level English speaker I might be wrong, but an "alias" means another (additional) name and this is NOT what import x as _x does.

Both import the same module or package, but

  • import x creates module object x

  • import x as _x creates module object _x (and does not touch x)

The latter helps to solve name clashes:

Example:

>>> math = 10
>>> import math as _math
>>> math
10
>>> _math.pi
3.141592653589793

It is sometimes used to support different implementations of the same API:

try:
    import xyz_fast as xyz
except ImportError:
    import xyz_standard as xyz

And most often just to simplify a name:

import datetime as dt
VPfB
  • 14,927
  • 6
  • 41
  • 75
1

Writing import x simply imports the module. When using any class or function from the module x, you have to define the module name like x.foo(). Adding the as _x makes _x an alias of the imported module's name. So, instead of x.foo() you can now write _x.foo(). Note that with the alias, you cannot write x.foo().

This helps shortening the module names in cases of large module names such as matplotlib.pyplot or scipy.signal etc. It's certainly much easier to write and read plt.plot() than matplotlib.pyplot.plot().

Abdur Rakib
  • 336
  • 1
  • 12