Python code security covers a wide range of concerns -- from protecting intellectual property in distributed scripts to preventing runtime attacks in web applications. This guide focuses on practical steps for developers at every level.
1. Never Hardcode Credentials
API keys, passwords, and tokens baked into .py files are one of the most common security mistakes. Use environment variables with os.environ.get('MY_API_KEY') or a .env file loaded with python-dotenv, and add .env to your .gitignore.
2. Obfuscate Before Distribution
When delivering Python scripts to clients or publishing automation tools, obfuscate the output to raise the bar against casual inspection. pyobfuscator.com can process your script in seconds, entirely in your browser with no data uploaded.
3. Use Virtual Environments
Always run Python projects inside a virtual environment (python -m venv .venv). This isolates dependencies and prevents malicious packages installed globally from interfering with your project.
4. Audit Dependencies
Run pip audit or use safety check to scan your dependencies for known vulnerabilities. Supply-chain attacks through compromised PyPI packages are increasingly common.
5. Validate All Inputs
Never pass user-supplied strings directly to eval(), exec(), subprocess with shell=True, or SQL queries. Use parameterized queries, subprocess argument lists, and explicit type validation.
6. Sign Your Distributed Scripts
For scripts distributed via download, publish a checksum (SHA-256) on your website. Users can verify integrity with sha256sum script.py before running.
7. Consider Cython for Critical Modules
Modules containing your most sensitive logic can be compiled to native extensions with Cython. The resulting .so or .pyd file is significantly harder to reverse than even obfuscated Python.