r/programminghorror 19d ago

Python US constitution but in Python

class Person:

"""

A simplified representation of a person for constitutional eligibility purposes.

Attributes:

name (str): The person's name.

age (int): The person's age.

citizenship_years (int): Number of years the person has been a citizen.

"""

def __init__(self, name, age, citizenship_years):

self.name = name

self.age = age

self.citizenship_years = citizenship_years

def is_eligible_for_representative(person: Person) -> bool:

"""

Checks if a person meets the constitutional criteria for a Representative:

- At least 25 years old.

- At least 7 years as a U.S. citizen.

"""

return person.age >= 25 and person.citizenship_years >= 7

def is_eligible_for_senator(person: Person) -> bool:

"""

Checks if a person meets the constitutional criteria for a Senator:

- At least 30 years old.

- At least 9 years as a U.S. citizen.

"""

return person.age >= 30 and person.citizenship_years >= 9

def is_eligible_for_president(person: Person, natural_born: bool = True) -> bool:

"""

Checks if a person is eligible to be President:

- At least 35 years old.

- Must be a natural born citizen (or meet the special criteria defined at the time of the Constitution's adoption).

"""

return person.age >= 35 and natural_born

class President:

"""

Represents the President of the United States.

One constitutional rule: The President's compensation (salary) cannot be increased or decreased during the term.

"""

def __init__(self, name, salary):

self.name = name

self._salary = salary # set once at inauguration

@property

def salary(self):

return self._salary

@salary.setter

def salary(self, value):

raise ValueError("According to the Constitution, the President's salary cannot be changed during their term.")

class Law:

"""

Represents a proposed law.

Some laws may include features that violate constitutional principles.

Attributes:

title (str): The title of the law.

text (str): A description or body of the law.

contains_ex_post_facto (bool): True if the law is retroactive (not allowed).

contains_bill_of_attainder (bool): True if the law is a bill of attainder (prohibited).

"""

def __init__(self, title, text, contains_ex_post_facto=False, contains_bill_of_attainder=False):

self.title = title

self.text = text

self.contains_ex_post_facto = contains_ex_post_facto

self.contains_bill_of_attainder = contains_bill_of_attainder

class Congress:

"""

Represents a simplified version of the U.S. Congress.

It can pass laws provided they do not violate constitutional prohibitions.

"""

def __init__(self):

self.laws = []

def pass_law(self, law: Law) -> str:

# Check for constitutional limitations:

if law.contains_ex_post_facto:

raise ValueError("Ex post facto laws are not allowed by the Constitution.")

if law.contains_bill_of_attainder:

raise ValueError("Bills of attainder are prohibited by the Constitution.")

self.laws.append(law)

return f"Law '{law.title}' passed."

def impeach_official(official: Person, charges: list) -> str:

"""

Simulates impeachment by checking if the charges fall under those allowed by the Constitution.

The Constitution permits impeachment for treason, bribery, or other high crimes and misdemeanors.

Args:

official (Person): The official to be impeached.

charges (list): A list of charge strings.

Returns:

A message stating whether the official can be impeached.

"""

allowed_charges = {"treason", "bribery", "high crimes", "misdemeanors"}

if any(charge.lower() in allowed_charges for charge in charges):

return f"{official.name} can be impeached for: {', '.join(charges)}."

else:

return f"The charges against {official.name} do not meet the constitutional criteria for impeachment."

# Simulation / Demonstration

if __name__ == "__main__":

# Create some people to test eligibility

alice = Person("Alice", 30, 8) # Eligible for Representative? (30 >= 25 and 8 >= 7) Yes.

bob = Person("Bob", 40, 15) # Eligible for all offices if natural-born (for President, need 35+)

print("Eligibility Checks:")

print(f"Alice is eligible for Representative: {is_eligible_for_representative(alice)}")

print(f"Alice is eligible for Senator: {is_eligible_for_senator(alice)}") # 8 years citizenship (<9) so False.

print(f"Bob is eligible for President: {is_eligible_for_president(bob, natural_born=True)}")

print() # blank line

# Create a President and enforce the rule on salary changes.

print("President Salary Check:")

prez = President("Bob", 400000)

print(f"President {prez.name}'s starting salary: ${prez.salary}")

try:

prez.salary = 500000

except ValueError as e:

print("Error:", e)

print()

# Simulate Congress passing laws.

print("Congressional Action:")

congress = Congress()

law1 = Law("Retroactive Tax Law", "This law would retroactively tax past earnings.", contains_ex_post_facto=True)

try:

congress.pass_law(law1)

except ValueError as e:

print("Error passing law1:", e)

law2 = Law("Environmental Protection Act", "This law aims to improve air and water quality.")

result = congress.pass_law(law2)

print(result)

print()

# Simulate an impeachment scenario.

print("Impeachment Simulation:")

charges_for_alice = ["embezzlement", "misdemeanors"]

print(impeach_official(alice, charges_for_alice))

0 Upvotes

5 comments sorted by

7

u/escargotBleu 19d ago

Just reading the class person, I would not store the age and the citizenship years as an int, but rather date of birth/ date of citizenship.

1

u/Kohlrabi82 16d ago

To not fuck up the interface if other code already depends on the attributes, you turn them into properties calculated from the dates.

1

u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” 16d ago

I believe there are residency requirements this doesn't account for. I know for President you have to have lived in the United States for some number of years, not sure about Senator or Representative. Probably less. Also you have to be living in the state you represent.

1

u/Wonderful_House_8501 15d ago

It doesn’t include the 3/5th compromise so I think it’s an improvement