Reference: https://www.cesarsotovalero.net/blog/i-am-switching-to-python-and-actually-liking-it.html
0. Preface
Nowadays, almost every professional university student learns to use Python to some extent. Before the emergence of ChatGPT, most students from non-computer and unrelated majors who learned Python were merely going through the motions. Everyone knew it was useful, but few understood just how useful it could be. Although I studied computer science, Python never became my primary learning objective.
However, with the advent of LLMs like ChatGPT, having a basic grasp of Python syntax, combined with AI assistance (where AI is actually the main force and you are playing support), seems to enable almost anyone to accomplish tasks. Even without working on large-scale projects, using Python to batch process xlsx and csv spreadsheets can save significant time, allowing you to dedicate those precious hours to more important activities like studying or relaxation.
Last night, a friend of mine who is currently pursuing a master’s degree mentioned that their teacher assigned them to write Python using VS Code. They are even from a liberal arts major. Clearly, this teacher is exceptionally outstanding, even outside their specific field of expertise, and is leading the way. As one of the code development tools most likely to be used by students after entering the corporate world, getting familiar with VS Code in advance is crucial. I believe that senior engineers, when mentoring interns, have all been frustrated by their inability to set up development environments, often forming a low first impression. We should be understanding, as starting is always the hardest part. Gaining early exposure to enterprise tools during school provides a significant head start.
I will not provide a detailed comparison of the currently mainstream development tools, as I do not consider myself proficient in all of them simultaneously, and my comparison would inevitably be biased. I will simply outline the tools I have used along a timeline. You can skip this section if you prefer:
- When I took an elective Python course in university, around 2017-2018, our school taught us to use Anaconda for environment management and Jupyter Notebook (installable via Anaconda) for writing code. It is a tool that integrates documentation and code, and it remains widely used in research and teaching scenarios today.
- However, since I learned programming before Python, I always felt that the mixed mode of documentation and code cells in Jupyter Notebook disrupted my coding flow. For actual code writing, I chose Spyder (installable via Anaconda), whose syntax hints and other features made me feel unprecedentedly comfortable.
- Later, I read tutorials online and noticed that many people were mentioning PyCharm. So, I installed PyCharm Community Edition to manage environments alongside my existing Anaconda installation. Its power is undeniable, but since it is the Community Edition, my small and medium-sized enterprises, which do not primarily use Python, have not licensed PyCharm Professional. Consequently, I could not apply it to enterprise development. I also believe it is not well-suited for students (programming geniuses excepted). From my observation, most students using PyCharm only utilize a fraction of its features, as it is a powerful tool designed for enterprises, equipped with a vast array of functionalities.
- As my programming skills improved, like many others, I began seeking a lighter setup and grew tired of Anaconda’s heaviness. By this time, I had a solid understanding of Python environments, libraries, and related concepts. I replaced Anaconda with miniconda, operated via the command line, managed environments using
environment.yml, and used VS Code for coding. However, this setup certainly did not offer the same seamless experience as PyCharm, largely because I had not configured the VS Code Python development environment to its optimal state. Nevertheless, my code was finally production-ready, which is a decisive advantage of VS Code. - Later, I discovered that installing certain low-level libraries using conda resulted in different behavior compared to installing them with pip. Additionally, some compilation installations failed with conda, whereas pip is the absolute industry standard. Therefore, I switched to using venv for environment management,
requirements.txtfor dependency management, and pip for installing libraries. For managing Python versions in production environments, I used pyenv, while continuing to use VS Code for coding. This brought me back to the very beginning, to the most fundamental approach. - After working with several open-source projects, I noticed that experienced developers were using poetry for environment management. So, I switched to poetry as well. It is based on venv and pip but uses
pyproject.tomlto manage environments and dependencies. - Later,
uvemerged and I noticed that almost all new open-source projects are usinguvfor environment management. It is also very easy to learn, so I naturally migrated touv. However, I faced a problem: a project at my company required using Python, which was clearly a commercial project. Moreover, I could no longer tolerate my half-configured, incomplete VS Code Python development environment; I needed an efficient one. I started frantically searching through open-source projects and asking AI, but the AI provided outdated or imperfect solutions. I realized that I needed to know the specific terms used in the perfect solution, and then use those terms to query the AI to get the best results. - Finally, I read the article linked in the references at the beginning, which guided me in setting up my current efficient development environment. Due to time constraints, I am not sure if I fully implemented the methods described in the article, but the current setup is sufficient for my needs.
Another reason to recommend VS Code is that it has the Github Copilot plugin built-in, which offers a generous free tier, automatically performing some code completions and Agent-assisted code generation. I do not recommend using Copilot while learning basic syntax, as it will make you lazy and prevent you from mastering the fundamentals. However, once you have mastered the basics, Copilot will significantly boost your programming efficiency. Github Copilot also has a paid version, which is not expensive. Students can use it for free by verifying their student status with a Github account.
For those who are not familiar, Github Copilot is currently a top-tier AI programming assistant (sometimes it may be second-tier, but it is always above average).
You do not need to treat this article as the ultimate authority, because I am a failing software engineer who is struggling to survive on the edge of the poverty line, enduring hunger and cold, not one of those successful software engineers with million-dollar annual salaries. Judging by my current status, this article lacks persuasiveness. Regardless, let us officially begin this article.
1. Install uv

I set up a fresh Windows 11 virtual machine to demonstrate this process. Naturally, Python is not installed on this VM yet. We will skip installing Python for now and go directly to the official uv documentation:
Since we are using Windows, select Windows here to display the Windows installation command. Click the copy button on the right to copy it.

Then, open PowerShell:

Paste the command you just copied into PowerShell, run it, and wait for the installation to complete.
2. Install VS Code
I'm sure everyone knows how to install VS Code, but I'll still include the official link below. Please avoid mistakenly installing so-called "green learning versions" from unofficial domestic sites. VS Code is completely free.
https://code.visualstudio.com/
During installation, you will be prompted to select options such as Add "Open with Code" action to Windows Explorer file context menu. It is recommended to check all of these options, as this allows you to right-click any file or folder and select "Open with Code," which is very convenient.
3. Install the VS Code Python Extension
In VS Code, click the Extensions button on the left side, search for "Python," and then install the Python extension published by Microsoft. Simply click Install, and it will automatically install several key Python extensions, including Pylance.

Once this extension is installed, VS Code will provide features such as Python syntax highlighting, code completion, and code navigation. When combined with GitHub Copilot, the coding experience becomes incredibly smooth.
For example, suppose I want to write a function for the Fibonacci sequence:

As you can see, I just typed def fibona, and it automatically completed the function body for me. All I need to do is press Tab to insert this code into the editor.
However, we are not done installing VS Code extensions yet. Please continue reading. Let's look at a real-world project example.
4. Create a project using uv
I created a demo directory on the desktop. Double-click to open the directory, type powershell in the address bar at the top, and press Enter. This will automatically open powershell in that directory.

Then I run:
uv init example

As you can see from the screenshot, it starts installing cpython 3.13.7 directly, which also means it will automatically install python 3.13.7 for you. If your team is using an older version, such as python 3.12, you can run uv init example --python 3.12 to specify the version. However, this is specific to uv's usage, which is outside the scope of this article. You can consult an AI assistant you trust, such as ChatGPT, for help.
After the installation is complete, you will notice a new example directory in the demo folder. Run the following command to enter that directory:
cd example
Then run the following command to open vscode in that directory
code .
You can then proceed with development comfortably.
In VS Code, you will see the Python version displayed in the bottom-right corner, along with the name of your virtual environment (in this case, the example environment we created), as shown in the figure below:

If this is not displayed as shown in my example—meaning there are no parentheses after the version number, no environment name is shown, only the version number is displayed, a different virtual environment name appears, or you are prompted to select a Python interpreter—it indicates that you have not selected the project's virtual environment as the default Python interpreter for the current project. You can click here and select the example virtual environment. As shown in the screenshot:

This step is very important, as it determines whether VS Code can correctly recognize your project environment.
5. ruff
ruff is a Python code quality checking tool developed by the team behind uv, similar to eslint and others. It helps you identify poor practices in your code and provides suggestions. It offers excellent performance, and both installation and configuration are very simple.
Open the command line in VS Code and run
uv add ruff --dev
As shown below:

We can see that we are indeed in the demo/example directory, so it is safe to run the above commands to install ruff. It is crucial to run the uv add command in the correct project directory; otherwise, it will result in an error or install the package into the wrong project.
After the installation is complete, we can run ruff in the terminal to check code quality.
6. A Bad Python Code Example
First, we create a new file bad_code.py, and then enter the following code:
import os, sys
import math
# 全局变量,不好的实践
person_name = "World"
COUNT = 5
# 函数有危险的可变默认参数
def add_items(items=[]):
items.append("item")
return items
def process_data( name, count):
# 这行代码太长了,难以阅读,而且有不一致的空格
print(f"开始为名为'{name}'的用户处理数据,该用户需要处理{count}个项目,这是一个非常长且不必要的消息,只是为了让这行代码的长度超过标准的88个字符限制。")
unused_variable = "我没有在任何地方被使用"
# 低效的循环和糟糕的格式
for i in range(count):
print("正在处理第 "+str(i +1)+" 个项目" )
# 另一个糟糕格式的例子
x=10
y = 20
result=x+y
print("结果是:", result)
# 多次调用带有可变默认参数的函数,以显示意外行为
print("第一次调用:", add_items())
print("第二次调用:", add_items()) # 这会意外地包含两个'item'!
# 主要逻辑没有被 if __name__ == "__main__": 保护
process_data(person_name, COUNT)
Then run the following in the terminal:
uv run ruff check
The results are shown in the screenshot below.

You can see a large number of errors reported. These are all due to code irregularities. However, we do not need to manually enter commands in the terminal to address this. We can configure VS Code extensions to display code errors directly within the VS Code editor, making it easier to automatically fix them or manually correct them.
7. Install the ruff plugin
Since I was writing this blog post during the National Day holiday, I had returned to my hometown and suddenly needed to go out on errands. For safety, I shut down my computer, which caused me to lose the temporary Windows virtual machine I was running in Docker. The following sections will be demonstrated on my Linux system (AnduinOS 1.3). However, since the environment setup portion is already complete, the subsequent steps are identical on Windows.

Search for ruff and install this plugin.
Next, we need some configuration to make it work. Press ctrl + shift + p, type settings json, and select Preferences: Open User Settings (JSON):

A JSON file will open automatically. Add the following content to it:
{
// 原有内容...
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.organizeImports": "explicit"
},
"editor.defaultFormatter": "charliermarsh.ruff",
},
}
Here is a brief explanation of this configuration:
"[python]": { ... }: This indicates that all settings within the brackets are specifically applied to Python files with the.pyextension, without affecting other file types (such as JavaScript, HTML, etc.)."editor.formatOnSave": true,: When this setting is set totrue, the Python file will be automatically formatted every time it is saved. The formatting rules are determined by the default formatter configured below (which is Ruff in this case)."editor.codeActionsOnSave": { ... },: This setting allows you to configure a set of "Code Actions" that are automatically executed when a file is saved."source.fixAll": "explicit",: This action applies all available automatic fixes to correct issues in the code. This typically includes fixing syntax or style issues detected by the linter (code checking tool). Setting it to"explicit"means this action will only be triggered when the file is explicitly saved (for example, using the keyboard shortcut Ctrl+S), rather than during automatic saves."source.organizeImports": "explicit",: This action automatically organizes import statements by removing unused imports and sorting the existing ones. This helps maintain code cleanliness and consistency. Similarly,"explicit"indicates that this action is only executed on explicit saves.
"editor.defaultFormatter": "charliermarsh.ruff",: This line specifies the default tool used for formatting Python code. Here, it is set tocharliermarsh.ruff, which is the unique identifier for the Ruff VS Code extension. Ruff is an extremely fast Python linter and code formatter written in Rust, capable of replacing multiple traditional tools such as Flake8, isort, and Black.
8. Experience ruff
Now, let's return to the bad_code.py file, as shown in the screenshot:

You can see that all irregularities are highlighted with yellow squiggly lines. If you have the Error Lens plugin installed, like I do, errors will be highlighted even more prominently, just as shown in the screenshot.

From top to bottom, the issues are:
- Imported some modules that are not used;
- Declared variables that are not used.
There are also other issues, such as global variables and the lack of an if __name__ == "__main__": guard, that are not flagged. This is because they are currently outside the scope of ruff's checks.
Since we configured editor.formatOnSave earlier, we only need to save the file (ctrl + s), and most of the issues will be automatically fixed.
After saving, you will notice that unused imports have been removed. However, unused_variable was not removed because it is considered an unsafe fix for ruff. During coding, you might declare a variable and save the file immediately before using it. Ruff will not automatically delete this variable because it might be used in subsequent code. If you have finished writing your code but are unsure which variables are unused and want to remove them, you can run uv run ruff check in the terminal to inspect the code, and then run uv run ruff check --unsafe-fixes --fix to force the fixes.
You might notice that your teacher's, senior's, or classmates' code shows many yellow and red errors in your VS Code, but they have no issues on their own computers. This is because their code quality is not high enough. However, you must absolutely avoid starting conflicts with them over these issues and damaging your relationships. You can recommend that they read this blog post.
Now, you can conveniently use VS Code and ruff to automatically improve your code quality! Congratulations!
9. Try Running It
In the terminal, you can directly use uv run xxx.py to run your Python code file.
uv run bad_code.py

10. More Complete Example
Now, I will introduce commonly used libraries for college students, such as numpy and pandas, and use streamlit to build a simple web application.
First, run the command in the terminal to install these 3 libraries:
uv add numpy pandas streamlit
Then create an app.py file and enter the following code:
import numpy as np
import pandas as pd
import streamlit as st
# 设置页面标题和图标
st.set_page_config(page_title="我的漂亮网页", page_icon="🎉")
# 主标题
st.title("欢迎来到我的 Streamlit 网页!")
# 副标题
st.header("这是一个用 uv 和 Python 构建的演示")
# 使用 Markdown 添加格式化文本
st.markdown("""
这是一个使用 `st.markdown` 创建的文本块。你可以轻松地:
- **加粗** 文本
- *斜体* 文本
- 创建列表
- 插入链接,例如 [Streamlit 官网](https://streamlit.io)
""")
# 添加一个交互式小部件
st.subheader("交互式滑块")
age = st.slider("请选择你的年龄", 0, 100, 25)
st.write(f"你选择的年龄是: {age} 岁")
# 显示一些数据
st.subheader("显示一个数据表格")
df = pd.DataFrame({
'第一列': [1, 2, 3, 4],
'第二列': [10, 20, 30, 40]
})
st.dataframe(df)
# 显示一个图表
st.subheader("显示一个简单的图表")
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
# 在侧边栏添加内容
st.sidebar.header("关于")
st.sidebar.info("这是一个在侧边栏的示例。")
Then run in the terminal:
uv run streamlit run app.py
On the first run, the terminal may prompt you to enter an Email address. Press Enter to skip it.
The terminal output is as follows:

Open http://localhost:8501 in your browser to view your web application!


11. Use Domestic Sources (Optional)
When you need to install large packages such as pytorch, the process may be slow or even fail. You can use a domestic mirror to speed up the installation.
Taking Tsinghua's tuna mirror as an example, here is the documentation:
https://mirrors.tuna.tsinghua.edu.cn/help/pypi/
Scroll down to the Astral uv section of the documentation and follow the instructions provided. However, the documentation may not be up to date. You can edit the pyproject.toml file in the project directory and add the following content
[[tool.uv.index]]
url = "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/"
default = true
12. Section
For research and learning, this environment is more than sufficient. You can comfortably write Python code in VS Code and enjoy the high-quality coding experience provided by ruff.
If you choose Anaconda, you can manage environments and packages through a graphical interface, which may be more beginner-friendly. However, it lacks the performance and flexibility of uv. Once you become familiar with uv and command-line operations, you will appreciate its power and simplicity. Moreover, if your collaborators clone the code, they only need to run uv sync to install all dependencies, eliminating the hassle of environment configuration.
13. ty (Optional)
Ruff is powerful, but its primary functions are code linting and code formatting. Here is a brief summary:
- Code Linting: Ruff can quickly detect errors, potential issues, non-compliant coding styles, and bad practices in Python code. It integrates rules from many popular tools (such as Flake8, isort, and pyupgrade) and reimplements them in Rust, significantly improving linting speed.
- Code Formatting: Ruff can also be used as a code formatter, aiming to be a direct replacement for Black. It automatically adjusts code formatting to comply with unified style guidelines, such as indentation and quote usage.
- Auto-fixing: For certain detected issues, such as unused imports, Ruff can automatically apply fixes, simplifying the developer workflow.
- Extremely Fast: Thanks to Rust's high performance, Ruff runs 10 to 100 times faster than traditional Python tools (such as Flake8 and Black), providing near-instant feedback for large projects.
However, when writing code intended for production environments, type checking is also very important for Python, which is a strongly typed, dynamically typed language. The team behind uv has also developed a tool named ty for type checking.
Ty is a high-performance Python type checker, also written in Rust, which also serves as a language server. Its core functions include:
- Static Type Checking: Ty's main function is to analyze type annotations in Python code and identify potential type-related errors before the code runs. This helps developers catch issues during the coding phase, such as passing data of the wrong type to a function.
- Improved Code Quality and Maintainability: By enforcing type conventions, Ty helps developers write more robust, understandable, and maintainable code.
- Language Server Features: As a language server, Ty can deeply integrate with code editors (such as VS Code) to provide real-time code diagnostics, auto-completion, and code navigation, thereby enhancing the development experience.
- High Performance: Similar to Ruff, Ty prioritizes speed as a core advantage, aiming to be significantly faster than existing Python type checkers, especially in large codebases.
The installation and usage of ty are similar to those of ruff. You can give it a try.
uv add ty --dev
You can run it in the terminal:
uv run ty check
to check for type issues.
They also provide a VS Code extension, but since it is still under development, it is highly unstable and may contain bugs. As a result, it has not yet been published to the VS Code extension marketplace. You can find it here:
https://github.com/astral-sh/ty-vscode
You can manually install it into VS Code for use. For specific instructions, you can search online for how to install VS Code extensions that are not available on the marketplace.
After installing ty, I decided not to install the VS Code extension for now, so I could experience ty's type checking functionality directly.
14. Experience ty
First, we enter the following code in the main.py file:
def calculate_sum(numbers: list[int]) -> int:
"""
接收一个整数列表并返回它们的总和。
"""
total = 0
for number in numbers:
total += number
return total
def get_user_scores() -> list[int | str]:
"""
模拟从某个 API 或用户输入获取数据。
注意:这里的返回类型被精确地标注为 list[int | str],
明确告诉类型检查器,列表内容可能是整数或字符串。
"""
return [100, 95, 88, "75"]
def main():
print("正在获取用户分数...")
scores = get_user_scores()
print("正在计算总分...")
# ty 会在这里报错!
# 因为 scores 的类型是 list[int | str],
# 而 calculate_sum 需要的类型是 list[int]。
total_score = calculate_sum(scores)
print(f"计算出的总分为: {total_score}")
if __name__ == "__main__":
main()
If run directly, it will report an error:
uv run python main.py
Error message:
正在获取用户分数...
正在计算总分...
Traceback (most recent call last):
File "/home/kit/projects/demo/example/main.py", line 35, in <module>
main()
File "/home/kit/projects/demo/example/main.py", line 29, in main
total_score = calculate_sum(scores)
^^^^^^^^^^^^^^^^^^^^^
File "/home/kit/projects/demo/example/main.py", line 7, in calculate_sum
total += number
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
However, no errors are reported in the VS Code code editor, even though we have installed ruff. As shown in the screenshot:

But if you run it in the terminal:
uv run ty check
As shown in the screenshot:

Now I install the ty plugin, then go back to the main.py file, as shown in the screenshot:

You can see that it throws an error immediately. You can fix the code based on the prompt.
15. Summary
That concludes the complete guide on how to quickly set up a Python development environment in VS Code. By using uv to manage environments and dependencies, ruff to improve code quality, and ty for type checking, you can significantly boost your Python programming efficiency and code quality.
However, this approach is suitable for those who already have a certain "awareness" of programming concepts. You should first clearly understand what an environment is, what a virtual environment is, what a terminal is, what a package is, and the difference between absolute and relative paths. Otherwise, you may find it difficult to follow the content of this article. Fortunately, we now have AI, and you can ask them questions freely. You can also visit the official documentation for uv, ruff, and ty to get more information.
uvdocumentation: https://docs.astral.sh/uv/ruffdocumentation: https://docs.astral.sh/ruff/tydocumentation: https://docs.astral.sh/ty/
If your goal in learning Python is scientific research, and your professors and classmates are still using tools like Anaconda, then you should primarily use Anaconda to avoid complications and better collaborate with them. However, if your goal in learning Python is to enter the corporate workforce, or if you are already working in a company, I strongly recommend using uv, ruff, and ty to set up your Python development environment. They will help you achieve twice the result with half the effort.
Comments (0)
No comments yet. Be the first to leave one!