Member-only story
Python: Hidden Features — part 1
Hi Everyone, In this article I will go throw couple of techniques or features which anyone can use in day to day coding.
In my journey through these Python features, I’ve uncovered tools that go beyond the ordinary, adding a touch of magic to our code.
Lets get started —
1. Function Objects
Everything in python is an object instantiated from some class. This also includes functions, but accepting this fact often feels counterintuitive at first.
Lets see an example —
def add_subject(name, subject, subjects=[]):
subjects.append(subject)
return {'name': name, 'subjects': subjects}
add_subject('person1', 'subject1')
add_subject('person2', 'subject2')
add_subject('person3', 'subject3')
output -
{'name': 'person1', 'subjects': ['subject1']}
{'name': 'person2', 'subjects': ['subject1', 'subject2']}
{'name': 'person3', 'subjects': ['subject1', 'subject2', 'subject3']}
Mutability in Python is possibly one of the most misunderstood and overlooked concepts.
The default parameters of a function are evaluated right at the time the function is defined. Thus, as soon as a function is defined, the function…