u11-slides-modules-packages Flashcards
What is the main purpose of modules in Python?
Modules allow you to reuse code (such as functions) in different programs and projects by putting the code into separate files.
What is the naming convention for Python modules?
Modules should use lowercase letters with underscores (if needed) for separation.
What is the naming convention for Python packages?
Packages should use lowercase letters, and underscores are discouraged.
What are the four main ways to import a module named ‘my_module’?
-
import my_module
(use as my_module.add(…))\n2.import my_module as mm
(use as mm.add(…))\n3.from my_module import add
(use as add(…))\n4.from my_module import add as my_add
(use as my_add(…))
What makes a directory a Python package?
A directory becomes a Python package when it contains an \_\_init\_\_.py
file (which can be empty or contain initialization code).
What happens when you import a module in Python?
All code within the module is executed when it’s imported.
How do you prevent code from executing when a module is imported?
Put the code inside an if \_\_name\_\_ == "\_\_main\_\_":
conditional block. This code will only run when the file is executed as a script, not when imported.
What are the different ways to import from a package?
-
import mypackage.my_module
\n2.import mypackage.my_module as mm
\n3.from mypackage import my_module
\n4.from mypackage.my_module import add
\n5.from mypackage.my_module import add as my_add
What is the difference between using import my_module
and from my_module import add
?
With import my_module
, you need to use the module name to access functions (my_module.add()), while with from my_module import add
, you can use the function directly (add()).
Does the \_\_init\_\_.py
file in a package need to be empty?
No, while it can be empty, it can also contain initialization code for the package.
How do you import and rename both a module and a specific function?
For module: import my_module as mm
\nFor function: from my_module import add as my_add
What is the syntax for importing from a nested package structure?
Use dot notation: from mypackage.my_module import add
or import mypackage.my_module
What’s the purpose of renaming modules or functions during import?
Renaming (using ‘as’) helps avoid naming conflicts and can make code more readable or concise when module names are long.
What’s the difference between a module and a package?
A module is a single Python file, while a package is a directory containing multiple modules and must include an \_\_init\_\_.py
file.
When running a Python file as a script, what is the value of \_\_name\_\_
?
When running a file directly as a script, \_\_name\_\_
equals "\_\_main\_\_"
. When the file is imported as a module, \_\_name\_\_
equals the module’s name.