Member-only story

Python: Hidden Features — part 1

Techniques programmers may not aware of

Pravash
4 min readNov 10, 2023

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Pravash
Pravash

Written by Pravash

I am a passionate Data Engineer and Technology Enthusiast. Here I am using this platform to share my knowledge and experience on tech stacks.

Responses (3)

Write a response

Mutability in Python is possibly one of the most misunderstood and overlooked concepts.

Yes, indeed. Many beginners make the mistake of using the default value to initialize an empty list, set or dict.

Hi.
There is are 2 typo (syntax errors) in the code snippets in section 1 of your article:
1)
def add_subject(name, subject subjects=[]):
subjects.append(subject)
return {'name': name, 'subjects': subjects}
there is a missing comma between, subject and

mutable default

The mistake is to mutate parameters at all. If there’s one good lesson from functional programming it’s that mutating operator *generally* severely reduce readability- the caller has to consider what else uses what is mutated - no mutation, no problem.