Gradescope Autograder for Python Assignments from Scratch
From the publisher’s feed, collected in the ZeroLabs newsroom.
When I first set up the autograder for Python for Data Science HWs on Gradescope, Gradescope’s official documentation was the only resource available — no walkthroughs, no examples of what breaks and why. This guide is what I wish had existed. It walks you through building and configuring autograder scripts for Python homework assignments on Gradescope, including the key design decisions and the subtle mistakes that are easy to make and hard to debug. As we are gearing up for Fall 2026, I thought I would share this resource with the community. The complete template used in this post is available on GitHub.The views expressed in this article are based on my personal experience and do not reflect the opinions of any institution or organization I am affiliated with.0. IntroductionA Gradescope autograder is a zip file containing four things:autograder.zip├── setup.sh # installs dependencies once when Docker image builds├── run_autograder # shell script Gradescope calls per submission├── run_tests.py # Python entry point that runs your tests└── tests/ └── test_submission.py # your actual test casesGradescope spins up a fresh Docker container for every student submission, runs setup.sh once during the build phase, then calls run_autograder for each submission. Your job is to get results.json written to /autograder/results/results.json — that JSON is what becomes the student's grade.The files are simple. The decisions inside them are not. Here is how to make them correctly, in the order you should think about them.Step 1: Install Your Dependenciessetup.sh runs once when Gradescope builds the Docker image for your assignment. It installs everything your test suite needs.#!/usr/bin/env bashset -euxo pipefailapt-get updateapt-get install -y python3 python3-pippython3 -m pip install --upgrade pippython3 -m pip install -r /autograder/source/requirements.txtexport MPLBACKEND=Agg # prevents matplotlib from trying to open a displaymkdir -p /autograder/resultsThe set -euxo pipefail line is important: it makes the script abort on any error and print every command as it runs. Without it, a failed apt-get or pip install silently continues and you end up debugging a broken environment with no indication of where it broke.Pin every dependency to an exact versionYour requirements.txt must use == for every library, not >= or no version at all:numpy==1.24.4scipy==1.10.1matplotlib==3.7.2gradescope-utils==0.5.0Why this matters: Gradescope rebuilds your Docker image only when you re-upload the zip. If a library releases a breaking update between when you built it and when a student submits late, unpinned dependencies will silently install the new version and your tests may produce different results or crash entirely. This is the kind of silent failure that is very hard to debug after the fact.To get exact versions from your working environment:pip freeze | grep -E "numpy|scipy|matplotlib"Put the version list in your assignment handout. Students working locally need to know what versions to use. If your autograder uses numpy==1.24.4 and a student runs your starter code with numpy==2.0.0, the behavior may differ and they will not understand why their code passes locally but fails on Gradescope. Something like:This assignment will be graded using Python 3.10 with the following libraries: numpy==1.24.4, scipy==1.10.1, matplotlib==3.7.2. To match the grading environment, run: pip install numpy==1.24.4 scipy==1.10.1 matplotlib==3.7.2Step 2: The Entry Pointrun_autograder This file is what Gradescope calls for every student submission. Keep it minimal — its only job is to invoke your Python test runner:#!/usr/bin/env bashset -euxo pipefailcd /autograder/sourcepython3 run_tests.pyDo not rename this file. Gradescope looks for it by name.Step 3 : Configure the Test Runnerrun_tests.pyThis is where you make two critical decisions: grade visibility and stdout visibility. Both are set here and affect every student.import osimport sysimport unittestfrom gradescope_utils.autograder_utils.json_test_runner import JSONTestRunner# Tell Python where to find the student's uploaded filesys.path.insert(0, '/autograder/submission')if __name__ == "__main__": suite = unittest.defaultTestLoader.discover('tests') os.makedirs('/autograder/results', exist_ok=True) with open('/autograder/results/results.json', 'w') as f: JSONTestRunner( stream=f, visibility='after_published', stdout_visibility='hidden', ).run(suite)Grade visibility: when do students see their scores?The visibility parameter in JSONTestRunner sets the default for all tests. Individual tests can override it with the @visibility decorator (covered in Step 4). The four options are:Option When students see it 'visible' Immediately after each submission 'after_due_date' After the assignment deadline passes 'after_published' After you click "Publish Grades" in Gradescope 'hidden' Never (instructors only)My recommended setup: set the default to 'after_published', then override 1–2 sanity-check tests to 'visible'. This means students get immediate confirmation they submitted correctly (visible tests), but your actual grading logic stays hidden until you release grades. This saves a lot of time especially when you are dealing with hundreds of students in a class — you review results once and publish, rather than fielding grade questions while the assignment is still open.stdout visibility: do not accidentally leak your test casesThis section is based on my own experience — in our course, we do not want to reveal hidden test cases to students.stdout_visibility controls whether students can see anything printed to standard output, from either their code or your test file. The danger is subtle:# In your test file — if stdout_visibility is 'visible', students see thisexpected = [0.1, 0.2, 0.3, 0.4, 0.5]print(f"Expected output: {expected}") # result = submitted.function_one(data)Even if you don’t print anything, students’ debug print() calls in their own code will show up too — which can inadvertently expose logic you didn't intend to share.Rule of thumb: keep stdout_visibility='hidden' for the entire assignment window. After you publish grades, switch to 'after_published' so students can use their own output to understand what went wrong.Step 4 — Write Your TestsEach test case needs two decorators: one for points, one for visibility.import unittestimport numpy as npfrom gradescope_utils.autograder_utils.decorators import weight, visibility, partial_creditimport student_submission as submitted # match the filename you told students to useclass TestPart1(unittest.TestCase): @weight(10) @visibility('after_published') def test_basic_correctness(self): result = submitted.my_function([1, 2, 3]) self.assertAlmostEqual(result, 6.0, places=4)Tell students exactly what to name their fileThe sys.path.insert line tells Python to look for imports inside /autograder/submission — the folder Gradescope puts the student's uploaded file in. Then in your test file, you import their code by name:import student_submission as submittedWhatever name you put in that import statement is the exact filename students must submit. If you write import homework, they must submit homework.py. If you write import hw3, they must submit hw3.py.Write this in bold on your assignment handout. Literally say:You must submit a single file named homework.py. Any other filename will cause the autograder to crash with an import error. This is the #1 source of student confusion and TA debugging time in my experience.Adding partial creditFor tests where “almost right” deserves some points, use @partial_credit instead of @weight. The key difference: you receive a set_score callback and call it yourself with however many points you want to award.@partial_credit(20)@visibility('after_published')def test_output_values(self, set_score=None): expected = [0.1, 0.2, 0.3, 0.4, 0.5] result = submitted.my_function([10, 20, 30, 40, 50]) if not isinstance(result, list): set_score(0) return if len(result) != len(expected): set_score(0) return correct = sum(abs(got - exp) set_score(20.0 * correct / len(expected))Three things to know: if you never call set_score(...), the student gets 0. You can call it anywhere in the test — the logic is just Python. And you can combine it with type penalties:score = 20.0if not isinstance(result, list): score *= 0.5 # 50% penalty for wrong type, then continue grading try: result = list(result) except Exception: set_score(0) returnThis pattern rewards students whose logic is correct but who returned a numpy array instead of a list — a very common minor mistake that would score 0 under a strict type check.Step 5 — Zip Your AutograderThe zip structure matters. Gradescope expects setup.sh, run_autograder, run_tests.py, and tests/ to be at the root of the zip — not inside a subdirectory. This is the correct command:cd autograder_template/zip -r ../autograder.zip setup.sh run_autograder run_tests.py requirements.txt tests/The common mistake is zipping the folder instead of the files inside it:# WRONG — Gradescope sees a subdirectory and can't find your fileszip -r autograder.zip autograder_template/There is no error message when you do it wrong — Gradescope just silently fails to find the required files. Always zip from inside the directory.Step 6 — Upload to GradescopeCreate a Programming Assignment in your course.Navigating to the Configure Autograder pageUpload the zip file and selecting the base Docker imageWaiting for the Docker image to build (typically 1–5 minutes)Confirming the build succeeded before moving to testingStep 7 — Test Before You ReleaseAfter the Docker image builds, do not release the assignment to students yet. Use the “Test Autograder” button on the Configure Autograder page and run three checks:Your own correct solution — all tests should pass at full score.A solution with deliberate errors — the specific failing tests should fail, others should pass.A solution with the wrong filename — the visible import sanity check should fail, making the problem obvious.Only set the release date after all three behave as expected.(Optional) One tip for after you releaseWatch the first 5–10 student submissions live from the Manage Submissions page. Common patterns in early errors often signal a problem in your autograder or assignment spec — better to catch it and regrade than to let 200 students hit the same wall. If you do catch a bug mid-assignment, fix it, re-upload the zip, and hit “Regrade All Submissions.” Gradescope re-runs your updated autograder on every existing submission. This is one of the platform’s genuinely great features.Dos and don’ts from building 20+ of theseDo group tests into classes by assignment section. Gradescope displays test results grouped by class name, which maps cleanly to assignment parts. class TestPart1, class TestPart2, etc. keeps the student view organized.Do use assertAlmostEqual for floats, never assertEqual. Floating point arithmetic produces small rounding differences across environments. places=4 is usually safe; tighten to places=6 if your function requires higher precision. A student whose implementation is numerically correct will fail a test they should pass if you use strict equality.Do seed random number generators every time you use np.random:@weight(20)@visibility('after_published')def test_end_to_end(self): np.random.seed(123) # data = np.random.exponential(3, 50) result = submitted.pipeline(data) self.assertAlmostEqual(result, 62.43, places=2)Without a fixed seed, the same student submission can produce different scores across reruns. When you hit “Regrade All Submissions” after a bug fix, unseeded tests can silently change scores.4. Do add a zero-point visible sanity check at the top of your test file. This is one of the most useful things you can do for students:@weight(0)@visibility('visible')def test_file_can_be_imported(self): """Checks your file was submitted with the correct name.""" self.assertTrue(hasattr(submitted, '__name__'))@weight(0)@visibility('visible')def test_required_functions_exist(self): required = ['function_one', 'function_two', 'function_three'] for fn in required: self.assertTrue(callable(getattr(submitted, fn, None)), msg=f"Missing or non-callable: {fn}")Students see these immediately after submitting. If either fails, they know the problem — wrong filename, function not defined, syntax error in their file — before they ever open a Piazza post.5. Do add an import check if you restrict libraries. If certain libraries are off-limits, check for them explicitly rather than waiting to discover violations during manual review. Learnt this the hard way:@weight(0)@visibility('visible')def test_no_forbidden_imports(self): import ast, inspect source = inspect.getsource(submitted) tree = ast.parse(source) for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: self.assertNotIn('forbidden_lib', alias.name, "Use of forbidden_lib is not allowed.")6. Don’t test your autograder only locally. Behavior can differ between your machine and the Gradescope Docker container — different OS, different default encodings, different file paths. Use the “Test Autograder” button on the Configure Autograder page. Submit a known-correct solution and a known-wrong solution before you release to students. The Debug via SSH option is invaluable when something fails only inside the container.7. Don’t zip the folder — zip the files. This is in the docs but easy to miss, and it produces a silent failure where Gradescope can’t find your files. Your zip must have setup.sh, run_autograder, run_tests.py, and tests/ at the root, not inside a subdirectory. The correct way on macOS/Linux:cd autograder_template/zip -r ../autograder.zip setup.sh run_autograder run_tests.py requirements.txt tests/If you zip the folder itself (zip -r autograder.zip autograder_template/), Gradescope sees a subdirectory and fails to find the required files.FAQsThese come up every semester without fail. I’ve included them verbatim as I send them to students.“My code works on my laptop but the autograder gives me an ImportError and scores 0 on everything”Symptom: You see something like this in Gradescope:ImportError: No module named 'sklearn'(or 'torch', 'pandas', 'cv2', 'requests', etc.)All tests: 0/100Even tests that have nothing to do with that library show 0.Why this happens: When the autograder imports your file, Python runs every top-level import statement immediately. If any import fails, Python stops right there and your entire file is treated as unloadable. Not a single function can be tested — every test scores 0.The grading environment only has the libraries listed in requirements.txt:numpy==1.24.4scipy==1.10.1matplotlib==3.7.2Any library not on that list is not installed. It does not matter that it is installed on your laptop. The autograder runs in an isolated Docker container with only what is listed above.How to fix it: Remove all imports of non-allowed libraries from your submission file and re-implement the logic using only the allowed libraries. If you are unsure whether a library is allowed, ask on the course forum before submitting.How to catch this locally before submitting: Create a fresh virtual environment and install only the allowed libraries:python3 -m venv test_envsource test_env/bin/activate # Windows: test_env\Scripts\activatepip install numpy==1.24.4 scipy==1.10.1 matplotlib==3.7.2python student_submission.pyIf your file imports anything not in that environment, you will see the ImportError locally — before Gradescope does.2. “I get a NameError / all my tests crash and I don’t know why”Symptom: You see something like this in Gradescope:Error during import: NameError: name 'function_one' is not defined(or: ZeroDivisionError / TypeError / etc.)All tests: 0/100Why this happens: Python executes every statement at the top level of a file the moment it is imported. When the autograder does import student_submission, it is not just reading your function definitions — it is running your entire file top to bottom.If you left debugging code outside of any function like this:result = function_one([1, 2, 3]) # line 8 — called before it's defineddef function_one(lst): # line 11 - defined too late return sum(lst)Python hits line 8 before it has even read function_one on line 11. It throws a NameError, the import crashes, and all tests score 0 — even the ones for functions that were perfectly correct.How to fix it: Your submission file should contain only import statements and function definitions. Nothing else at the top level. If you want to test your functions locally, wrap your test calls in an if __name__ == "__main__": block, which Python skips during import:import numpy as npdef function_one(lst): return sum(lst)def function_two(lst, key): mean = sum(lst) / len(lst) return {key: mean}# This block is IGNORED by the autograder - safe to leave inif __name__ == "__main__": print(function_one([1, 2, 3])) print(function_two([1, 2, 3], 'a'))How the guard works: when you run python student_submission.py directly, Python sets __name__ to "__main__" and the block runs. When the autograder does import student_submission, Python sets __name__ to "student_submission" and skips the block entirely. This is the standard Python pattern for separating reusable code from one-time scripts — use it in every file you write.Questions or corrections? Leave a comment below.Gradescope Autograder for Python Assignments from Scratch was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.