Skip to content

Generators/people.py doesn't run on Python 3 (print statements, xrange, time.clock, mem_profile) #232

@subham-hq

Description

@subham-hq

Problem

@CoreyMSchafer

Generators/people.py (companion to the Generators tutorial video) fails on every currently supported Python version:

  1. print 'Memory (Before): ...'SyntaxError: Missing parentheses in call to 'print' — Python 2 print statements fail at parse time, so the file can't even be imported.
  2. xrangeNameError — removed in Python 3.
  3. time.clock()AttributeError — deprecated in 3.3, removed in 3.8.
  4. import mem_profileModuleNotFoundError — this local helper module isn't included in the Generators folder, so the script fails even after fixing the syntax.

Proposed update (tested on Python 3.14)

import os
import random
import time

import psutil  # pip install psutil

names = ['John', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business']


def memory_usage_mb():
    process = psutil.Process(os.getpid())
    return process.memory_info().rss / 1024 / 1024


print(f'Memory (Before): {memory_usage_mb():.2f} MB')


def people_list(num_people):
    result = []
    for i in range(num_people):
        person = {
            'id': i,
            'name': random.choice(names),
            'major': random.choice(majors),
        }
        result.append(person)
    return result


def people_generator(num_people):
    for i in range(num_people):
        person = {
            'id': i,
            'name': random.choice(names),
            'major': random.choice(majors),
        }
        yield person


# t1 = time.perf_counter()
# people = people_list(1_000_000)
# t2 = time.perf_counter()

t1 = time.perf_counter()
people = people_generator(1_000_000)
t2 = time.perf_counter()

print(f'Memory (After) : {memory_usage_mb():.2f} MB')
print(f'Took {t2 - t1:.6f} seconds')

Changes

  • print statements → print() with f-strings
  • xrangerange
  • time.clock()time.perf_counter() (the modern benchmarking clock)
  • mem_profile → inline memory_usage_mb() using psutil, keeping the same single third-party dependency the video used
  • 10000001_000_000

The list vs. generator demo behaves identically: the list version shows the ~300+ MB memory jump, the generator version stays flat and returns instantly.

Happy to open a PR — either updating the file or adding a people_py3.py alongside it so the original stays in sync with the video.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions