Skip to content
This repository was archived by the owner on Jul 2, 2024. It is now read-only.

Commit 6a592ca

Browse files
committed
Add mutable/immutable demos
1 parent 9d16e0e commit 6a592ca

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

src/basics/__init__.py

Whitespace-only changes.

src/basics/scripts/__init__.py

Whitespace-only changes.

src/basics/scripts/demo_mutable.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
This module demonstrates the mutable nature of objects
3+
4+
"""
5+
6+
import logging
7+
from typing import Any, List, Optional
8+
9+
logging.basicConfig(level=logging.DEBUG)
10+
logger = logging.getLogger(__name__)
11+
12+
13+
def change_mutable_v1(value: Any, mutable: List[Any]) -> List[Any]:
14+
"""This function will change mutable argument"""
15+
16+
mutable.append(value)
17+
return mutable
18+
19+
20+
# noinspection PyDefaultArgument
21+
def change_mutable_v2(value: Any,
22+
mutable: Optional[List[Any]] = []) -> List[Any]:
23+
"""This function will change default mutable object"""
24+
25+
mutable.append(value)
26+
return mutable
27+
28+
29+
def change_valid(value: Any,
30+
mutable: Optional[List[Any]] = None) -> List[Any]:
31+
"""
32+
This function wouldn't change defaults,
33+
but will change mutable argument.
34+
"""
35+
36+
mutable = mutable or []
37+
mutable.append(value)
38+
39+
return mutable
40+
41+
42+
if __name__ == "__main__":
43+
mutable_obj1 = []
44+
change_mutable_v1(1, mutable_obj1)
45+
mutable_obj1 += [2] # [1, 2], because it was changed by "change_mutable"
46+
47+
logger.info(f"{mutable_obj1 = }")
48+
49+
mutable_obj2 = change_mutable_v2(10) # expected: [10]
50+
mutable_obj3 = change_mutable_v2(20) # expected: [20], but [10, 20]
51+
52+
logger.info(f"{mutable_obj2 = }")
53+
logger.info(f"{mutable_obj3 = }")
54+
55+
mutable_obj4 = change_valid(100) # expected: [100]
56+
mutable_obj5 = change_valid(200) # expected: [200]
57+
mutable_obj6 = change_valid(3, mutable_obj1) # expected: [1, 2, 3]
58+
59+
logger.info(f"{mutable_obj4 = }")
60+
logger.info(f"{mutable_obj5 = }")
61+
logger.info(f"{mutable_obj6 = }")

0 commit comments

Comments
 (0)