The first real Python problem most Java developers hit isn’t syntax. It’s this:
ModuleNotFoundError: No module named 'anthropic'
…right after running pip install anthropic. The package is installed, just not where the code is running. Python’s tooling works differently from Maven, and once you see the model, problems like this disappear.
This is part 13, the last part of Python for Java Developers. Part 12 covered async and await.
The Maven world, mapped
| Java / Maven | Python |
|---|---|
A .java file in a package folder |
A .py file: a module |
| A package folder | A folder of modules: a package |
import com.acme.rag.Retriever; |
from rag.retriever import Retriever |
pom.xml |
pyproject.toml (older: requirements.txt) |
| Maven Central | PyPI (pypi.org) |
mvn dependency:add, editing the pom |
uv add / pip install |
~/.m2 shared cache + a classpath per build |
A virtual environment (.venv) per project |
| Lock file (none by default) | uv.lock |
public static void main |
if __name__ == "__main__": |
mvn exec:java |
uv run main.py / python main.py |
| JDK version per project (SDKMAN, toolchains) | uv python install 3.12, .python-version |
| Checkstyle + Spotless | ruff |
| JUnit | pytest |
Modules, packages and imports
Every .py file is a module, named after the file. A folder of modules is a package:
my-ai-app/
pyproject.toml
.env # API keys, never committed
app/
__init__.py # marks app/ as a package (can be empty)
main.py
llm.py
retriever.py
tests/
test_retriever.py
Imports come in a few shapes:
import json # whole module: json.loads(...)
from pathlib import Path # one name: Path(...)
from app.llm import ask # from your own package
from app.retriever import Retriever, top_k
import numpy as np # with a short alias
Python looks for app starting from the folder you run from (and from installed packages), so run your code from the project root. Avoid from module import *: it pulls in every name and hides where things come from.
The main guard
public class Main {
public static void main(String[] args) {
System.out.println(ask("hello"));
}
}def main():
print(ask("hello"))
if __name__ == "__main__":
main()Every module has a __name__. It’s "__main__" only when you run that file directly; when another file imports it, it’s the module’s name, and the block is skipped. So the guard means: “run main() if this file is the program, but not when it’s imported”. It’s how a Python file declares its main method.
Virtual environments: the one thing to get right
Maven keeps every version of every library in ~/.m2 and builds a classpath for each project, so two projects can use different versions of the same library without trouble.
Python works differently: pip install puts a package into an environment, a folder of installed packages tied to one Python interpreter. If everything goes into the system Python, every project shares one set of packages, and the day two projects need different versions, one breaks.
So the rule is: one virtual environment per project, always. A virtual environment is just a .venv folder inside the project with its own interpreter link and its own packages. Add it to .gitignore; it’s rebuilt from the dependency file, like target/.
The classic way, with tools that ship with Python:
python -m venv .venv # create it
source .venv/bin/activate # use it (Windows: .venv\Scripts\activate)
pip install anthropic fastapi # install into it
pip freeze > requirements.txt # record exact versions
“Activating” just puts .venv first on your PATH, so python and pip mean the project’s ones. Forget to activate, and you install into one environment while running in another. That’s the ModuleNotFoundError from the start of this article.
uv: Maven’s job, in one fast tool
uv is a newer tool, written in Rust, that does what Maven does for Java: it creates the environment, manages dependencies, writes a lock file, installs Python versions and runs your code. And it never needs activating.
uv init my-ai-app # new project with pyproject.toml
cd my-ai-app
uv add anthropic fastapi # add dependencies (creates .venv, updates pyproject.toml and uv.lock)
uv add --dev pytest ruff # dev-only dependencies, like Maven's test scope
uv run main.py # run inside the project's environment
uv run pytest # run tests
uv sync # recreate .venv exactly from uv.lock (after git clone)
uv remove fastapi # remove a dependency
uv python install 3.12 # install a Python version
uv run always uses the project’s .venv, so “installed in the wrong environment” can’t happen. New projects increasingly use uv; older ones use pip and requirements.txt, or tools like Poetry. You’ll be able to read all of them now.
pyproject.toml: Python’s pom.xml
After uv init and a couple of uv add commands, it looks like this:
[project]
name = "my-ai-app"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"anthropic>=0.40",
"fastapi>=0.115",
]
[dependency-groups]
dev = ["pytest>=8", "ruff>=0.8"]
TOML is a simple config format, closer to a .properties file than to XML. The exact resolved versions of everything, including transitive dependencies, live in uv.lock. Commit both files.
API keys and .env files
Never put keys in code. Put them in a .env file in the project root, add .env to .gitignore, and load it at startup with python-dotenv (uv add python-dotenv):
ANTHROPIC_API_KEY=sk-...
MODEL=claude-sonnet-5-5
import os
from dotenv import load_dotenv
load_dotenv() # reads .env into the environment
model = os.getenv("MODEL", "claude-sonnet-5-5") # like System.getenv, with a default
Most AI SDKs read their key from the environment automatically, so after load_dotenv() you often don’t touch the key at all.
Two tools worth adding on day one
- ruff formats and lints your code, replacing Checkstyle, Spotless and a dozen older Python tools:
uv run ruff format .anduv run ruff check .. - pytest runs tests. A test is a function whose name starts with
test_, using plainassert:
# tests/test_retriever.py
from app.retriever import top_k
def test_top_k_returns_best_first():
hits = [{"score": 0.2}, {"score": 0.9}]
assert top_k(hits, 1) == [{"score": 0.9}]
Traps for Java developers
ModuleNotFoundErrorafter installing. The package went into a different environment than the one running your code. Useuv run, or check whichpythonis active withwhich python(where pythonon Windows).- Naming your file after a package. A file called
anthropic.py,json.pyorrandom.pyin your project is imported instead of the real package. Rename it. - Committing
.venv. It’s large and machine-specific. Commitpyproject.tomland the lock file; others runuv sync. - Installing into the system Python.
sudo pip installcan break tools your operating system depends on. Newer systems refuse it. Always use a virtual environment. - Running from the wrong folder. Imports like
from app.llm import askwork from the project root. Runuv run python -m app.mainrather thancd app && python main.py.
Key takeaways
- A
.pyfile is a module, a folder of them is a package, andfrom pkg.module import nameimports. if __name__ == "__main__":is Python’s main method.- Dependencies go into a virtual environment, one per project. This is the key difference from Maven.
uvcreates the environment, managespyproject.tomlanduv.lock, and runs your code withuv run.- Keys go in
.env, loaded withpython-dotenvand read withos.getenv. - Add ruff and pytest as dev dependencies from the start.
Frequently asked questions
What is the Python equivalent of Maven?
There isn’t one official tool, but uv covers the same ground: project creation, dependencies, a lock file, Python versions and running code. The classic built-in combination is venv plus pip plus a requirements.txt file. Poetry is another popular option.
What is a virtual environment in Python?
A folder (usually .venv) containing a link to a Python interpreter and its own installed packages. Each project gets one, so different projects can use different package versions without conflicts.
What is pyproject.toml?
The standard project file for Python, similar to pom.xml: it holds the project’s name, version, required Python version and dependencies, plus settings for tools like pytest and ruff.
Why do I get ModuleNotFoundError after pip install?
Almost always because pip installed the package into one Python environment and your code runs in another. Activate the project’s virtual environment before installing and running, or use uv add and uv run, which always use the project’s environment.
What does if name == “main” mean?
It checks whether the file is being run directly. Python sets __name__ to "__main__" for the file you run and to the module’s name for imported files, so code inside the block runs only when the file is the program, like Java’s main method.
You’ve finished the series
That’s all 13 parts. You can now read nearly any Python file and know what each line does and which Java idea it maps to: syntax, collections, functions, classes, errors, comprehensions, type hints, decorators, generators, async and tooling.
Want to build AI in your first language too? Continue with Java for AI Engineers, or go back to the start of this series: the 10 differences that matter.
Comments