Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ name = "pypi"
[packages]
examplepackagefb1258 = {file = ".", editable = true}
build = "*"
pytest = "*"
coverage = "*"
pytest-cov = "*"
twine = "*"
pytest = "*"

[dev-packages]

Expand Down
205 changes: 115 additions & 90 deletions Pipfile.lock

Large diffs are not rendered by default.

186 changes: 125 additions & 61 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,90 +1,154 @@
![Python build & test](https://github.com/nyu-software-engineering/python-package-example/actions/workflows/build.yaml/badge.svg)
# 🥠 PyFortuneCookie

# Python Package Example
A fun Python package that generates your **daily fortune cookie** — complete with a lucky number and color!
Perfect for learning how to build and run Python packages.

This package was created by generally following the [Packaging Python Projects](https://packaging.python.org/en/latest/tutorials/packaging-projects/) with the addition of some [pipenv setup](https://packaging.python.org/en/latest/tutorials/managing-dependencies/) to manage virtual environments.
---

## How this package was created
## 📦 Installation

1. [Install pipenv](https://packaging.python.org/en/latest/tutorials/managing-dependencies/#managing-dependencies), [build](https://packaging.python.org/en/latest/tutorials/packaging-projects/#generating-distribution-archives), and [twine](https://packaging.python.org/en/latest/key_projects/#twine) if not already installed.
2. create directory structure for the package like that below, where `examplepackagefb1258` is replaced with your package's name. This name must be uniquely yours when uploaded to [PyPI](https://pypi.org/). Better to avoid hyphens or underline characters (`-` or `_`) in the package name, as these can create problems when importing. The parent directory name (the repository name) - `python-package-example` in this case - is not relevant to the package name.
Clone or download this repository, then install it locally (in editable mode):

```bash
pipenv install
pipenv run pip install -e .
````

If you don’t have **pipenv**, install it first:

```bash
pip install pipenv
```
python-package-example/
|____README.md
|____LICENSE
|____pyproject.toml
|____tests
|____src
|____examplepackagefb1258
|______init__.py
|______main__.py
|____wisdom.py

---
💻 Run Locally (for teammates)

If you want to run this project on your own machine (e.g., to test or modify it):

# 1️⃣ Clone the repository
```bash
git clone https://github.com/your-username/pyfortunecookie.git
cd pyfortunecookie
```

3. Make `__init__.py` an empty file.
4. Enter the text of a [copyright license of your choosing](https://choosealicense.com/) into `LICENSE`.
5. Add settings in `pyproject.toml` suitable for a `setuptools`-based build and add metadata fields to this file - see the example in this repository.
6. Put your own custom module code into `src`/`examplepackagefb1258`/`wisdom.py` or whatever filename(s) you choose for the module(s) that live within your package.
7. Optionally add a `__main__.py` file to the package directory, if you want to be able to run the package as a script from the command line, e.g. `python -m examplepackagefb1258`.
8. Build the project by running `python -m build` from the same directory where the `pyproject.toml` file is located.
9. Verify that the built `.tar` archive has the files you expect your package to have (including any important non-code files) by running the command: `tar --list -f dist/examplepackagefb1258-0.0.7.tar.gz`, where `examplepackagefb1258-0.0.7` is replaced with your own package name and version.
10. Create an account on [TestPyPI](https://test.pypi.org/) where one can upload to a test repository instead of the production PyPI repo.
11. Create a [new API token](https://test.pypi.org/manage/account/#api-tokens) on TestPyPI with the "Scope" set to “Entire account”. Save a copy of the token somewhere safe.
12. [Upload your package](examplepackagefb1258) to the TestPyPI repository using twine, e.g. `twine upload -r testpypi dist/*`
13. twine will output the URL of your package on the PyPI website - load that URL in your web browser to see your packaged published - make sure the `README.md` file looks nice on the web site.
# 2️⃣ Install pipenv and dependencies
```bash
pip install pipenv
pipenv install
```
# 3️⃣ Enter the virtual environment
```bash
pipenv shell
```
# 4️⃣ Run the tests (optional, to verify everything works)
```bash
pipenv run pytest
```bash
# 5️⃣ Run the package
```bash
python3 -m pyfortunecookie
```

Every time you change the code in your package, you will need to rebuild and reupload it to PyPI. You will need to build from a clean slate and update the version number to achieve this:
💡 You can exit the environment anytime with:

1. delete the autogenerated `dist` directory
2. delete the autogenerated `src/*.egg-info` directory
3. update the version number in `pyproject.toml` and anywhere else it is mentioned (do a find/replace)
4. build the package again with `python -m build`
5. upload the package again with `twine upload -r testpypi dist/*`
```
exit
```
---

## 🚀 Usage

Repeat as many times as necessary until the package works as expected.
You can run PyFortuneCookie either from the **command line** or directly as a **Python module**.

If updating version numbers is tedious, you may consider using [bumpver](https://pypi.org/project/bumpver/#configuration-setup) - a tool that can automate some parts of updating version numbers.
### ▶️ Option 1: Run as command-line tool

```bash
pipenv run pyfortunecookie
```

**Once complete, upload to the real PyPI** instead of the TestPyPI repository.
### ▶️ Option 2: Run as a Python module

## How to install and use this package
```bash
pipenv run python -m pyfortunecookie
```

Try [installing and using your package](https://packaging.python.org/en/latest/tutorials/packaging-projects/#installing-your-newly-uploaded-package) in a separate Python project:
### ▶️ Option 3: Import and use functions in your code

1. Create a `pipenv`-managed virtual environment and install the latest version of your package installed: `pipenv install -i https://test.pypi.org/simple/ examplepackagefb1258==0.0.7`. (Note that if you've previously created a `pipenv` virtual environment in the same directory, you may have to delete the old one first. Find out where it is located with the `pipenv --venv` command.)
1. Activate the virtual environment: `pipenv shell`.
1. Create a Python program file that imports your package and uses it, e.g. `from examplepackagefb1258 import wisdom` and then `print(wisdom.get())` (replace `wisdom` and `get()` with any module name and function that exists in your package) .
1. Run the program: `python3 my_program_filename.py`.
1. Exit the virtual environment: `exit`.
```python
from pyfortunecookie.core import get_fortune, get_lucky_number, get_color

Try running the package directly:
print(get_fortune())
print(get_lucky_number())
print(get_color())
```

1. Create and activate up the `pipenv` virtual environment as before.
2. Run the package directly from the command line: `python3 -m examplepackagefb1258`. This should run the code in the `__main__.py` file.
3. Exit the virtual environment.
---

## How to run unit tests
## 🌟 Example Output

Simple example unit tests are included within the `tests` directory. To run these tests...
When you run the command:

1. Install `pytest` into the virtual environment, e.g. `pipenv install pytest`
1. Run the tests from the main project directory: `python3 -m pytest`.
1. Tests should never fail. Any failed tests indicate that the production code is behaving differently from the behavior the tests expect.
```bash
pipenv run pyfortunecookie
```

## How to calculate code coverage
You might see something like this:

To calculate the "code coverage" of the unit tests, use the `coverage` package.
```
🥠 Welcome to PyFortune Cookie!

1. Install `coverage` and `pytest-cov` into the virtual environment, e.g. `pipenv install coverage pytest-cov`
1. Run the tests with a coverage report included at the bottom, e.g. `python3 -m pytest --cov=.`
Today's fortune: Your curiosity will lead to something amazing today ✨
Your lucky number: 37
Your lucky color: Lavender
```

Each time you run it, you’ll get a new random fortune, number, and color!

---

## 🧠 Features

| Function | Description |
| -------------------- | -------------------------------- |
| `get_fortune()` | Returns a random fortune message |
| `get_lucky_number()` | Generates a random lucky number |
| `get_color()` | Returns a random lucky color |

---

## 🧪 Run Tests

Make sure everything works properly with:

```bash
pipenv run pytest
```

All tests are located inside the `tests/` directory.

---

## 🛠 Project Structure

```
pyfortunecookie/
├── src/
│ └── pyfortunecookie/
│ ├── __init__.py
│ ├── __main__.py
│ └── core.py
├── tests/
│ └── test_core.py
├── Pipfile
├── pyproject.toml
└── README.md
```

## Pro tip
---

While working on the package code, and verifying it behaves as expected, it can be helpful to install the package in "_editable_" mode so that changes to the package are immediately updated in the virtual environment.
## 👩‍💻 Author

- To do this, run `pipenv install -e .` from the main project directory.
Created by **Sina Liu** (NYU SWE Fall 2025)
-- a practice for SWE Project 3! 🌈

## Continuous integration

This project has a continuous integration workflow that builds and runs unit tests automatically with every _push_ of the code to GitHub.
18 changes: 9 additions & 9 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "examplepackagefb1258"
description = "An example of a package developed with pipenv, built with build using setuptools, uploaded to PyPI using twine, and distributed via pip."
version = "0.1.2"
name = "pyfortunecookie"
description = "A fun fortune cookie generator with lucky number and color"
version = "0.1.0"
authors = [
{ name="Foo Barstein", email="[email protected]" },
{ name="SinaL0123", email="[email protected]" },
]
license = { file = "LICENSE" }
readme = "README.md"
keywords = ["python", "package", "build", "tutorial"]
keywords = ["fortune", "fun", "demo"]
requires-python = ">=3.7"
classifiers = [
"Programming Language :: Python :: 3",
Expand All @@ -24,9 +24,9 @@ classifiers = [
dev = ["pytest"]

[project.urls]
"Homepage" = "https://github.com/nyu-software-engineering/python-package-example"
"Repository" = "https://github.com/nyu-software-engineering/python-package-example.git"
"Bug Tracker" = "https://github.com/nyu-software-engineering/python-package-example/issues"
"Homepage" = "https://github.com/your-username/python-package-practice"
"Repository" = "https://github.com/your-username/python-package-practice.git"
"Bug Tracker" = "https://github.com/your-username/python-package-practice/issues"

[project.scripts]
examplepackagefb1258 = "examplepackagefb1258.__main__:main"
pyfortunecookie = "pyfortunecookie.__main__:main"
19 changes: 0 additions & 19 deletions src/examplepackagefb1258/__main__.py

This file was deleted.

52 changes: 0 additions & 52 deletions src/examplepackagefb1258/wisdom.py

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@
For more information, see the official documentation:
https://docs.python.org/3/reference/import.html#regular-packages
"""
from .core import get_fortune, get_lucky_number, get_color

__all__ = ["get_fortune", "get_lucky_number", "get_color"]
15 changes: 15 additions & 0 deletions src/pyfortunecookie/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""
In Python packages, this file called __main__.py is run when the package is run
directly from command line, as opposed to importing it into another program.
"""

from pyfortunecookie.core import get_fortune, get_lucky_number, get_color

def main():
print("🥠 Welcome to PyFortune Cookie!\n")
print(f"Today's fortune: {get_fortune()}")
print(f"Your lucky number: {get_lucky_number()}")
print(f"Your lucky color: {get_color()}")

if __name__ == "__main__":
main()
37 changes: 37 additions & 0 deletions src/pyfortunecookie/core.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import random

_FORTUNES = [
"Today is a good day to start small.",
"A pleasant surprise is waiting for you.",
"Your code will compile on the first try.",
"Help others and luck will help you.",
"Take a short walk; ideas will follow.",
"A cup of coffee will solve half your problems. ☕",
"You will soon discover a hidden strength. 💪",
"Your curiosity is your superpower. 🔍"
]

_PALETTES = {
"soft": ["peach", "mint", "lavender", "sky", "lemon"],
"bold": ["crimson", "indigo", "emerald", "amber", "teal"],
"mono": ["black", "white", "gray"]
}

def get_fortune(rng: random.Random | None = None) -> str:
"""Return a random fortune sentence."""
rng = rng or random
return rng.choice(_FORTUNES)

def get_lucky_number(seed: int | None = None, min_value: int = 1, max_value: int = 99) -> int:
"""Return a lucky number (optionally deterministic if seed provided)."""
if min_value > max_value:
raise ValueError("min_value must be <= max_value")
rng = random.Random(seed) if seed is not None else random
return rng.randint(min_value, max_value)

def get_color(palette: str = "soft", rng: random.Random | None = None) -> str:
"""Return a lucky color from the selected palette."""
if palette not in _PALETTES:
raise ValueError(f"Unknown palette '{palette}'. Valid: {', '.join(_PALETTES)}")
rng = rng or random
return rng.choice(_PALETTES[palette])
Loading