50 lines
1.3 KiB
Markdown
50 lines
1.3 KiB
Markdown
---
|
||
title: variableNamingBestPractices
|
||
tags:
|
||
- python
|
||
- variables
|
||
- syntax
|
||
- naming
|
||
- constants
|
||
aliases:
|
||
- naming conventions
|
||
- snake_case
|
||
- ALL_CAPS
|
||
- variable reassignment
|
||
---
|
||
|
||
> [!important] Naming Best Practices
|
||
> - Use **snake_case** for variables: `user_name`, `email_count`
|
||
> - Use **ALL_CAPS** for constants: `MAX_CONNECTIONS = 10`
|
||
> - Python doesn't enforce constants, but the convention is **SCREAMING_SNAKE_CASE**
|
||
> - Define constants at the **module level** for global visibility
|
||
>
|
||
> - Avoid unintentional reassignment. Python allows variable re-binding to different types:
|
||
> ```python
|
||
> my_var = 1
|
||
> my_var = "Now I'm a string"
|
||
> ```
|
||
>
|
||
> - Variables don’t auto-update in expressions. You must reassign explicitly:
|
||
> ```python
|
||
> bacon = bacon + 1
|
||
> # or
|
||
> bacon += 1
|
||
> ```
|
||
>
|
||
> > [!example] Reassignment Example
|
||
> > ```python
|
||
> > first_variable = 1
|
||
> > first_variable = 2
|
||
> > print(type(first_variable)) # <class 'int'>
|
||
> > print(first_variable) # 2
|
||
> >
|
||
> > first_variable = "I'm a string now! I used to be an integer."
|
||
> > print(type(first_variable)) # <class 'str'>
|
||
> > print(first_variable)
|
||
> > ```
|
||
>
|
||
> > [!info] Related Notes
|
||
> > [[variableNamingRules]]
|
||
> > [[typeConversions]]
|
||
> > [[pythonSyntaxOverview]]
|