Skip to content

Instantly share code, notes, and snippets.

@DevTiw37
Created July 21, 2024 08:33
Show Gist options
  • Save DevTiw37/70cc55bcf201e8cc599347b2de78c227 to your computer and use it in GitHub Desktop.
Save DevTiw37/70cc55bcf201e8cc599347b2de78c227 to your computer and use it in GitHub Desktop.
Difference between import math and from math import *

The difference between import math and from math import * in Python lies in how they bring the module's functions and variables into your namespace:

  1. import math:

    • This imports the entire math module.
    • You need to prefix the functions with math. when using them.
    • Example:
      import math
      result = math.sqrt(16)
      print(result)  # Output: 4.0
  2. from math import *:

    • This imports all functions and variables from the math module directly into your current namespace.
    • You can use the functions without the math. prefix.
    • Example:
      from math import *
      result = sqrt(16)
      print(result)  # Output: 4.0

Key Differences:

  • Namespace Pollution: from math import * can lead to namespace pollution, where functions or variables from the math module might overwrite existing ones in your code, or vice versa².
  • Readability: import math makes it clear which module a function comes from, improving code readability and maintainability³.

For these reasons, it's generally recommended to use import math or selectively import only the needed functions, like from math import sqrt⁴.

If you have more questions about Python or anything else, feel free to ask!

Source: Conversation with Copilot, 21/7/2024 (1) python - Difference between "import X" and "from X import *"? - Stack .... https://stackoverflow.com/questions/12270954/difference-between-import-x-and-from-x-import. (2) ‘import’ vs ‘from import’ in Python — What’s The Difference?. https://www.codingem.com/python-difference-between-import-and-from-import/. (3) Understanding Python Import Statements: - pythontwist.com. https://pythontwist.com/understanding-python-import-statements-from-import-vs-import. (4) python - Difference between import math and from math import - Stack .... https://stackoverflow.com/questions/64164361/difference-between-import-math-and-from-math-import.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment