Interview question
What is a virtual environment and why should you use one? Virtual environment क्या है और इसे क्यों use करना चाहिए?
Answer
A virtual environment is an isolated Python installation with its own set of packages, separate from the system-wide Python and other projects - preventing dependency conflicts between projects.
# Creating a virtual environment (built into Python 3.3+)
python -m venv myenv
# Activating it
# On Windows:
myenv\Scripts\activate
# On macOS/Linux:
source myenv/bin/activate
# Once activated, pip installs go into THIS environment only
pip install requests
pip list # shows only packages installed in this venv
# Deactivating
deactivate| Without venv | With venv |
|---|---|
| All projects share one global package set | Each project has its own isolated packages |
| Project A needs Django 3, Project B needs Django 4 - CONFLICT | Each project can use different versions freely |
| Risk of breaking system Python tools | System Python stays untouched |
# Saving and restoring exact dependencies
pip freeze > requirements.txt # export current packages and versions
pip install -r requirements.txt # install exact same packages elsewhere
# Alternative tools: virtualenv (more features), conda, poetry, pipenvVirtual environment एक isolated Python installation है जिसका अपना packages का set होता है, system-wide Python और अन्य projects से अलग - projects के बीच dependency conflicts रोकता है।
# Virtual environment बनाना
python -m venv myenv
# Activate करना
# Windows:
myenv\Scripts\activate
# macOS/Linux:
source myenv/bin/activate
# Activate होने पर pip installs सिर्फ इसी environment में जाती हैं
pip install requests
pip list
# Deactivate करना
deactivate| venv के बिना | venv के साथ |
|---|---|
| सभी projects एक global package set share करते हैं | हर project के अपने isolated packages |
| Project A को Django 3, B को Django 4 चाहिए - CONFLICT | अलग versions आराम से use हो सकते हैं |
pip freeze > requirements.txt
pip install -r requirements.txtWas this answer clear?