Thursday, March 18, 2021

Python Morsels: importing a module

Related article:

Transcript

Let's talk about importing modules in Python.

Importing a module

Python comes bundled with a whole bunch of modules called the Python standard library. We're going to import the math module from the standard library:

>>> import math

The math module has a function called sqrt that we can use to get the square root of a number.

We can't currently call the sqrt function directly:

>>> sqrt(25)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined

To use the sqrt function need to call math.sqrt:

>>> math.sqrt(25)
5.0

Whenever you import a module, Python will make just one variable, the name of the module that we imported, (math in our case) which points to a module object:

>>> math
<module 'math' from '/usr/lib/python3.9/lib-dynload/math.cpython-39-x86_64-linux-gnu.so'>

Module object

When we imported the math module, we got a module object, and that module object has attributes.

Our math module object has a pi attribute:

>>> math.pi
3.141592653589793

And an e attribute:

>>> math.e
2.718281828459045

And a sqrt attribute:

>>> math.sqrt
<built-in function sqrt>
>>> math.sqrt(25)
5.0

And a whole bunch of other attributes. Everything within the math module lives as an attribute on that math module object.

Importing specific module elements

After you've imported the math module, you'll need to put math. before the name of anything you'd like to use in the module. If you don't want to have to type math. something every time you use something in the math module, instead of using an import statement you could use a from-import statement.

So instead of this:

>>> import math

You could do this:

>>> from math import sqrt

Now we'll have access to the sqrt function directly:

>>> sqrt(25)
5.0

Or if we wanted to import multiple things we could put commas between them:

>>> from math import sqrt, pi

We now have pi and sqrt:

>>> pi
3.141592653589793
>>> sqrt(25)
5.0

but we don't have e:

>>> e
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'e' is not defined

Because we didn't import e from the math module.

Summary

If you want to import a module in Python, you'll need to use an import statement. But unless you want to type the name of the module over and over (each time you access something in the module), you might want to use the from syntax for importing instead: from MODULE_NAME import THINGS_FROM_MODULE.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...