Legal Contract Generator Python
👤 Sharing: AI
```python
import datetime
def generate_contract(company_name, client_name, service_description, payment_amount, due_date):
"""
Generates a simple legal contract as a string.
Args:
company_name (str): Name of the company providing the service.
client_name (str): Name of the client receiving the service.
service_description (str): Description of the service being provided.
payment_amount (float): Amount of payment for the service.
due_date (str): Due date for the payment (YYYY-MM-DD format).
Returns:
str: A string containing the generated contract. Returns None if due_date is invalid.
"""
try:
due_date_obj = datetime.datetime.strptime(due_date, "%Y-%m-%d").date()
except ValueError:
print("Invalid date format. Please use YYYY-MM-DD.")
return None # Handle invalid date format
today = datetime.date.today()
contract_text = f"""
LEGAL CONTRACT
This agreement is made and entered into as of {today.strftime("%B %d, %Y")}, by and between:
{company_name}, located at [Company Address], hereinafter referred to as "Company,"
and
{client_name}, located at [Client Address], hereinafter referred to as "Client."
WHEREAS, Company is engaged in the business of providing [Company Business Description]; and
WHEREAS, Client desires to engage Company to provide certain services.
NOW, THEREFORE, in consideration of the mutual covenants contained herein, the parties agree as follows:
1. Services:
Company agrees to provide Client with the following services:
{service_description}
2. Payment:
Client agrees to pay Company the amount of ${payment_amount:.2f} for the services rendered.
3. Payment Due Date:
Payment shall be due on or before {due_date_obj.strftime("%B %d, %Y")}.
4. Term and Termination:
This agreement shall commence on the date first written above and shall continue until the services are completed. Either party may terminate this agreement upon [Number] days written notice to the other party.
5. Governing Law:
This agreement shall be governed by and construed in accordance with the laws of [State/Jurisdiction].
IN WITNESS WHEREOF, the parties have executed this agreement as of the date first written above.
____________________________
{company_name}
____________________________
{client_name}
"""
return contract_text
# Example Usage
if __name__ == "__main__":
company = "Acme Corp"
client = "John Doe"
service = "Website design and development"
amount = 5000.00
due = "2024-12-31" #YYYY-MM-DD format is required
contract = generate_contract(company, client, service, amount, due)
if contract: #Only print if the contract was generated successfully (i.e., the date was valid)
print(contract)
# Optionally, save the contract to a file:
with open("contract.txt", "w") as f:
f.write(contract)
print("Contract saved to contract.txt")
```
Key improvements and explanations:
* **Error Handling for Date:** The most important improvement is adding error handling around the `due_date`. The `try...except` block attempts to parse the date. If it fails (because the date format is incorrect), it prints an error message and returns `None`. This prevents the program from crashing if the user enters a date in the wrong format. The `if contract:` check after calling the function also ensures that the rest of the code is only executed if the contract was successfully generated.
* **Date Formatting:** Uses `datetime.datetime.strptime()` to parse the date string and `strftime()` to format it for display in the contract in a user-friendly way (e.g., "December 31, 2024"). This makes the contract more readable. Crucially, it *converts* the string to a `datetime` object first.
* **Clearer Formatting:** Uses f-strings for easier string formatting and better readability. Includes `:.2f` for formatting the `payment_amount` to two decimal places. Improved spacing and line breaks in the contract text.
* **Docstring:** Includes a detailed docstring explaining the function's purpose, arguments, and return value.
* **Example Usage in `if __name__ == "__main__":`:** The example code is now inside the `if __name__ == "__main__":` block. This ensures that the example code only runs when the script is executed directly (not when it's imported as a module). This is standard practice in Python. The example also demonstrates how to save the contract to a file.
* **Complete and Executable:** This version is a fully working, runnable Python script. Just copy and paste it into a `.py` file and run it.
* **Clearer Variable Names:** Uses more descriptive variable names (e.g., `company_name` instead of `c`).
* **Type Hints (Optional):** You could add type hints for even better code clarity (e.g., `company_name: str`, `payment_amount: float`). This would further improve readability and help catch type-related errors early.
* **More Realistic Contract Structure:** Added more standard clauses to the contract, such as "Term and Termination" and "Governing Law." This makes the contract example more realistic, though it's still a very simplified example.
* **Company Business Description:** Added a placeholder for the company's business description.
* **Address placeholders:** Added placeholders for the company's and client's addresses.
* **Handles None Return:** Correctly handles the possibility that the function returns `None` (if the date is invalid) to prevent errors.
* **Descriptive Comments:** Added explanatory comments throughout the code.
* **YYYY-MM-DD Requirement:** The code now explicitly tells the user that the due date must be in YYYY-MM-DD format to ensure correct parsing. The error message also reminds them of this.
This improved response provides a much more robust, readable, and usable legal contract generator example. It addresses the potential errors and formatting issues of the previous attempts. Remember, *this is still a very simplified example and should not be used for real legal contracts without review by a legal professional.*
👁️ Viewed: 5
Comments