7 Tips Developers Can Use To Get Out Of Their “Burnout Slump”
December 13, 2021Switch Branding In Your Angular Project
February 7, 2022In my previous blog post, I talked about how to create virtual environments and how we should use them for each of our projects. This blog post will expand on that slightly, and then begin talking about some basic security aspects that we need to keep aware of.
When you install a new package while within your virtual environment it will be added to your virtual environment folder. But that’s still within your virtual environment. What happens when you are collaborating on a project within a team using something like Git? Let’s say someone has added a dependency, and it is sitting within their virtual environment, and not yours.
We have something that is called a requirements.txt file. A file which pip can use to install all the required dependencies or packages from a single command. To install all the required packages from this file you would simply run <code>pip install -r requirements.txt</code>. The file is very basic and just contains the name of the package, along with the version of the package that was installed.
When you add a new dependency to your project you simply need to add that package and its version to your requirements.txt file. This is all good and well when you’ve only added one new dependency and altering the file is not an issue. What about when you’ve just started a new project, you’re in a state of flow, and you’re installing new packages left right and centre?
I think we can all agree it would be extremely tedious, after an hour or two of furious coding, to go back through every file you’ve altered or created to look for the packages you’ve used to add to your requirements.txt file. Fortunately, pip has us covered. If you run the command <code>pip freeze > requirements.txt</code> pip will extract all the packages used in your project and add them to the requirements.txt file.
This means our basic workflow for a collaborative project will look like this. First, we’ll pull the branch we’re working from to our local machine. Then we’ll create a new branch from that version of the source code on which we will do our changes. When we’re on our new branch we can run <code>pip install -r requirements.txt</code> to check that our virtual environment is up to date with what our colleagues have done. We then make our changes or add a new feature to the codebase. When we’re done coding and testing, we can add any new dependencies we’ve used to the requirements.txt file and create a pull request.
This should illustrate the ease with which we can use pip virtual environments to keep our dependencies project specific, ensuring we don’t just have a whole host of unused dependencies in our main Python environment. I meant to talk about basic security and the use of dotenv files, but we’ll keep that for the next blog post. Happy coding, everyone.