7.2 Importing names

3 min readjune 24, 2024

Python's system is a powerful feature that allows you to organize and reuse code efficiently. By importing specific functions or entire modules, you can access a wide range of pre-built functionality to enhance your programs.

Understanding how to modules and manage packages is crucial for writing clean, efficient Python code. This knowledge enables you to leverage the vast ecosystem of Python libraries, both built-in and third-party, to solve complex problems with ease.

Importing Modules and Functions in Python

Importing specific functions

Top images from around the web for Importing specific functions
Top images from around the web for Importing specific functions
  • Use
    [from](https://www.fiveableKeyTerm:From)
    keyword followed by module name and
    import
    to import specific functions from a module
    • Syntax:
      from module_name import function_name
    • from [math](https://www.fiveableKeyTerm:Math) import [sqrt](https://www.fiveableKeyTerm:sqrt)
      imports only
      sqrt
      function from
      math
      module
  • Allows using imported function directly without prefixing it with module name
    • After importing
      sqrt
      from
      math
      , use
      sqrt(4)
      instead of
      math.sqrt(4)
  • Import multiple functions from a module by separating them with commas
    • from math import sqrt, [sin](https://www.fiveableKeyTerm:sin), [cos](https://www.fiveableKeyTerm:cos)
      imports
      sqrt
      ,
      sin
      , and
      cos
      functions from
      math
      module

Prevention of name collisions

  • Name collisions occur when imported names conflict with existing names in code or other imported modules
  • Use
    as
    keyword to create an for imported module or function to avoid name collisions
    • Syntax:
      import module_name as alias
      or
      from module_name import function_name as alias
    • import [matplotlib.pyplot](https://www.fiveableKeyTerm:matplotlib.pyplot) as plt
      creates alias
      plt
      for
      matplotlib.pyplot
      module
  • Using aliases prevents name collisions and makes code more readable by providing shorter or more descriptive name
  • Another way to prevent name collisions is to import entire module and use module name as prefix when accessing its functions or variables
    • import math
      and then use
      math.sqrt(4)
      to avoid conflicts with other
      sqrt
      functions

Specific vs entire module imports

  • Importing specific functions:
    • Advantages:
      • Use imported functions directly without prefixing with module name, making code more concise
      • Reduces risk of name collisions by only importing required functions
      • Can make code more readable by explicitly showing which functions are used from a module
    • Disadvantages:
      • Requires knowing exact names of functions to import
      • May result in longer import statements if importing many functions from a module
  • Importing entire modules:
    • Advantages:
      • Access all functions and variables from module using module name as prefix
      • Requires less knowledge of specific function names within module
      • Can make shorter if using many functions or variables from module
    • Disadvantages:
      • Increases risk of name collisions if module contains names that conflict with code or other imported modules
      • May make code less readable if module name is long or not descriptive enough
      • Can potentially import unnecessary functions or variables not used in code

Package Management and Libraries

  • Python's provides built-in modules for common tasks
  • Third-party libraries extend Python's functionality beyond the standard library
  • Use (Python installer) to install and manage third-party libraries
  • Packages are collections of modules organized in directories
    • The file in a directory indicates it should be treated as a package
  • Relative imports allow importing modules within the same package using dot notation

Key Terms to Review (23)

__init__.py: __init__.py is a special Python file that serves as an initializer for a package, allowing the interpreter to recognize a directory as a package and enabling the import of modules within that directory. This file can be empty or contain initialization code for the package, helping to organize code into logical namespaces. It plays a crucial role in module management, including the importing of names and locating modules within Python's package structure.
Alias: An alias is a shorthand or alternative name that can be used to reference a module or object in Python. It simplifies the process of importing and using modules, making code more readable and manageable. When you create an alias, you can easily call functions or classes from a module without needing to type the full module name each time.
As: The term 'as' is a versatile word in the English language that can serve various grammatical functions, such as a conjunction, preposition, or adverb. In the context of the Python programming language, 'as' is primarily used in the process of importing names from modules, as well as when using modules with classes.
Cos: The cosine function, commonly denoted as 'cos', is a trigonometric function that calculates the ratio between the adjacent side and the hypotenuse of a right-angled triangle. It is one of the fundamental trigonometric functions, along with sine and tangent, and is widely used in various mathematical and scientific applications, including the context of importing names in Python.
Datetime: datetime is a module in Python that provides classes for working with dates, times, and time intervals. It allows you to perform various operations and manipulations on date and time data, making it a crucial tool for tasks that involve handling temporal information.
From: The term 'from' is a preposition used to indicate the starting point, origin, or source of something. It is a fundamental word in the English language that plays a crucial role in various programming concepts, particularly in the context of importing names and using modules with classes.
Import: The term 'import' in the context of Python programming refers to the process of bringing in and using functionality, data, or modules from external sources within a Python script or program. It allows developers to leverage existing code and resources to enhance their own applications.
Import statement: An import statement allows you to bring in modules and their functions for use in your Python program. It is essential for accessing pre-built functionalities like those in the math module.
Math: Math is the study of quantities, structures, space, and change. It involves the use of numbers, symbols, and logical reasoning to quantify and analyze various phenomena. Math is a fundamental language that underpins many scientific and technological fields, and it is essential for understanding and solving problems in a wide range of contexts.
Matplotlib.pyplot: matplotlib.pyplot is a popular library in Python that provides a set of functions and tools for creating high-quality, publication-ready plots and visualizations. It is a part of the larger matplotlib library and is widely used in data analysis, scientific computing, and data visualization tasks.
Module: A module is a self-contained unit of code in a programming language that encapsulates related functionality, data, and logic. Modules allow for the organization and reuse of code, promoting modularity and maintainability in software development.
Name collision: A name collision occurs when two separate modules have functions, classes, or variables with the same name, leading to ambiguity and potential errors in the program. This typically happens during the import process.
Namespace: A namespace is a way to organize and manage the naming of variables, functions, and other identifiers in a programming language. It provides a way to group related elements together and ensure that their names are unique within the program, preventing naming conflicts.
Package: In the context of Python, a package is a collection of modules that provides a structured way to organize and distribute code. Packages allow for the grouping of related modules, making it easier to manage and reuse code within a larger application or project.
Pip: Pip is a package installer for Python that allows users to easily install, upgrade, and remove Python packages and their dependencies. It is a crucial tool for managing Python libraries and modules, enabling seamless integration of external software components into Python projects.
Random: Random is a concept in computer programming that refers to the generation of a sequence of numbers or values that appear to be unpredictable and without any discernible pattern. It is a fundamental tool used in various applications, including simulations, cryptography, and decision-making processes.
Relative Import: Relative import is a way of importing modules in Python that allows you to reference other Python files within the same project hierarchy. This is particularly useful when working with complex projects that have multiple interdependent modules.
Selective Import: Selective import is a feature in Python that allows you to import specific names or functions from a module, rather than importing the entire module. This can be useful for reducing the size of your code and improving its readability by only including the necessary components.
Sin: In the context of the topic 7.2 Importing names, the term 'sin' refers to the act of importing a name from a module or package without explicitly specifying the module or package name. This can lead to potential naming conflicts and make the code less readable and maintainable.
Sqrt: The square root function, denoted as 'sqrt', is a mathematical operation that calculates the positive square root of a given number. It is a fundamental function in mathematics and programming, with applications in various fields, including geometry, physics, and engineering.
Standard Library: The standard library is a collection of pre-written, pre-tested code that comes bundled with the Python programming language. It provides a wide range of functionality, from file input/output to network communication, without the need for additional downloads or installations.
Third-Party Library: A third-party library is a pre-written software package or module developed by an external organization or individual that can be integrated into a software application to provide additional functionality or features. These libraries are often used in the context of programming languages, such as Python, to extend the core capabilities of the language and simplify development tasks.
Wildcard Import: A wildcard import, also known as a star import or an all-import, is a way of importing all the names defined in a module into the current namespace. This allows you to access the imported names without having to specify the module name every time.
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Glossary