Python Import Libraries: Three Syntax Versions

2 minutes read

Python has a few syntax ways to import libraries/modules: import library (as ...) or from library import .... For newcomers, it may be confusing which one to use in which case. Let me explain.


1. Import Full Library Without Alias

import math

This is the most simple.

It means you will use multiple features from the math library, and you're ok with calling them with math.xxxxx syntax:

math.sqrt(64)
x = math.ceil(math.pi)

2. Import Full Library With Alias

import pandas as pd

This means you will use multiple features from the pandas library and you want to call them in a shorter syntax:

df = pd.read_csv("salaries.csv") # instead of pandas.read_csv()

3. Import Specific Library "Sub-Package" With Alias

Some libraries consist of multiple "sub-libraries", also called "sub-modules" or "sub-packages". You may want to import only one of them.

import matplotlib.pyplot as plt

You may not want to use the full matplotlib but import a specific feature from it, like pyplot. Again, there's an alias to avoid calling its methods with a full name every time:

plt.scatter(x, y) # instead of matplotlib.pyplot.scatter(x, y)

4. From Library Import Function

If you want to load only a specific function (or other object) from the library, you can do it like this:

from sklearn.model_selection import train_test_split

This means that you're importing, in most cases, a single function from the library to usually call it immediately afterward.

Full code:

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=0)

Another example:

from sklearn.linear_model import LinearRegression
model = LinearRegression()

This import syntax is often used to load a specific method in the middle of the script instead of importing the entire library, which is typically done at the very top as the first action of the script.


Geovane Krüger avatar

Hello, I'm trying to use a python script inside Laravel, But I'm not able to use import from a library in any way.

I'm calling the script like this (it works):

$process = new Process(['/usr/bin/python3', base_path() . '/app/Python/critical_power_3_parameters.py']); $process->run(); if (!$process->isSuccessful()) { throw new ProcessFailedException($process); } $data = $process->getOutput(); dd($data); });

And in the app/Python folder I have:

import numpy as np # Coefficients of the equations A = np.array([[3, 1], [1, 2]]) # Constants on the right side of equations b = np.array([9, 8]) # Solving the system of equations x = np.linalg.solve(A, b) print("Solution:", x)

Can you help me with something like that?