How to quit the interactive Python session?
exit()
Two steps to open a venv project of python?
how to check which python interpreter is currently active in my venv?
How to activate the python interpreter of the venv from terminal?
source ./Scripts/activate.\Scripts\activate.bat.\Scripts\activate.ps1If trying to activate Python interpreter results in permission error in powershell (scripts not allowed to execute), then what to do?
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
How to leave the virtual environment of Python?
deactivate.\Scripts\deactivate.batdeactivateCreate a virtual environment in Python by the name “myenv”.
python3 -m venv myenv
It creates a myenv/ directory in the current working directory.
To run a Python module from CLI, it must have _ .
Create a module that displays your name and run it from CLI using -m flag
“__main__” entry point.
\_\_name\_\_ == '\_\_main\_\_'
How to print the module name (mytool) when running the module usingpython -m mytool command
print(sys.argv[0])
What is a positional argument in python CLI?
How is it different from other (optional) arguments?
Positional argument
* doesn’t use --.
* is required by default.
* Order matters.
Non-positional argument
* starts with -- or -.
* often has a default value
*
CLI command:python -m mymodule coffee --name Sahil
CLI output:searching coffee for Sahil
def main():
parser = argparse.ArgumentParser(description="Search items for you")
parser.add_argument(
"itemname",
help="item to search for",
nargs="?",
default="coffee"
)
parser.add_argument("--name", help="Your name", required=True)
argsObject = parser.parse_args()
print(f"Searching {argsObject.itemname} for {argsObject.name}...")How to specify that argument is optional, i.e., at most one (0 or 1) argument is allowed, while adding argument to ArgumentParser?
nargs
parser = argparse.ArgumentParser() parser.add_argument( "--foo", nargs="?", default="value" )
What are lazy imports in Python?
Importing modules inside a function or conditionally, makes the import lazily evaluated.
def process_data():
import pandas as pdAs best practice, keep imports scoped to the respective modules and entrypoint of the application lean.
What is entrypoint of a Python application?
main.py
Imports like pandas are inside run_app, which
main.py contains following code:
if \_\_name\_\_ == "\_\_main\_\_":
run_app()The run_app() function contains import to pandas. During during container startup with CMD ["python", "main.py"]
, will the pandas module be loaded?
No.
pandas is only loaded when run_app() is called — not during container startup.
Python normally doesn’t allow breaking a statement across lines unless inside parentheses, brackets, or braces.
Wrapping the chaining call of functions inside _ lets you split it neatly across multiple lines
parentheses
(…)
Everything inside the parentheses is treated as one single expression. Without parentheses, you’d need ugly backslashes \ for line continuation.