Shopping cart

Tips and Tricks

Cool Python Tricks to Show Off

June 2, 20255 Mins Read
11

You might say, “I’d rate myself 9/10 in Python.” But how well do you really know the language if you haven’t pushed its boundaries or explored its more obscure features?

Don’t worry. I’m not here to gatekeep—I’m here to guide you through some of Python’s quirks and features that make it so uniquely powerful. Welcome to the world of Pythonic wizardry.

TL;DR

Python’s flexibility allows for unusual syntax and behavior not typically seen in languages like Java or C++. For example, in my earlier blog “Why Does Python Allow print = 123?”, I explained how Python lets you reassign built-in functions—something that seems insane, but is entirely legal. This is thanks to Python’s philosophy: “Everything is an object” and “Explicit is better than implicit.”


1. Dynamic Reassignment

Let’s begin with one of Python’s signature quirks—assigning functions to variables.

def greet():
print("Hi")

say_hello = greet
say_hello() # Output: Hi

That’s basic. Now let’s crank it up:

print('foo')  # Output: foo

def my_logger(*args, sep=' ', end='\n'):
with open('./logs', 'a') as f:
output = sep.join(str(arg) for arg in args)
f.write(output + end)

print = my_logger
print('foo') # Logs to file instead of printing

Yes, you just hijacked print(). And yes, you can undo this:

del print  # Restores the original built-in print

You can even modify built-in behavior globally:

__builtins__.open = lambda *args, **kwargs: print("File access blocked!")
open("test.txt") # Output: File access blocked!

Use Cases

  • Unit testing (mocking built-ins)
  • Custom REPLs or sandboxes
  • Monkey patching
  • Dependency injection simulations
  • Middleware wrapping
  • Partial application of functions

2. Lambdas Inside Lists

Anonymous functions (lambda) are common, but Python lets you do this:

funcs = [lambda x=i: x for i in range(3)]
print([f() for f in funcs]) # Output: [0, 1, 2]

Here’s a more advanced use case:

def create_handlers(configs):
return [lambda event, conf=conf: f"{conf} handled {event}" for conf in configs]

configs = ['handler1', 'handler2', 'handler3']
handlers = create_handlers(configs)

for i, handler in enumerate(handlers):
print(handler(f"event_{i}"))

Use Cases

  • Dynamic GUI callbacks (e.g., in Tkinter, PyQt)
  • API endpoint generation
  • Command-line interfaces
  • Job scheduling systems

3. Extended Iterable Unpacking

Standard unpacking:

a, b, c = [1, 2, 3]

Extended unpacking:

first, second, third, *middle, second_last, last = range(100)

Now middle holds everything between third and second_last.

Use Cases

  • CLI argument parsing
  • NLP token trimming
  • CSV row unpacking
  • Debugging/tracing logs

4. Swapping Without a Temp Variable

The traditional way:

temp = b
b = a
a = temp

Pythonic way:

a, b = b, a

Use Cases

  • Sorting
  • Game state toggling
  • Anywhere you need to swap values

5. Chained Comparisons

This:

if 6 > my_var > 2:
...

Is equivalent to:

if my_var > 2 and my_var < 6:
...

But it reads more naturally.


6. Using else with Loops

for i in range(3):
if i == 99:
break
else:
print("Did not break!") # This will run

Also works with while loops and try blocks.

Key Difference

  • try ... else: runs only if no exception occurs
  • loop ... else: runs only if loop wasn’t broken

Use Cases

  • Retry loops
  • Search loops with early exits
  • Cleanup logic without flags

7. Walrus Operator (:=)

Introduced in Python 3.8, it allows assignment within expressions:

if (n := len("hello")) > 3:
print(n) # Output: 5

Use Cases

  • Avoid redundant calculations
  • Cleaner loop conditions
  • Debugging or logging without breaking logic

8. Metaclasses

Metaclasses define how classes behave, just like classes define object behavior:

class MyMeta(type):
def __new__(cls, name, bases, dct):
dct['magic'] = lambda self: "✨"
return super().__new__(cls, name, bases, dct)

class MyClass(metaclass=MyMeta):
pass

print(MyClass().magic()) # Output: ✨

Use Cases

  • Attribute validation
  • Declarative ORMs
  • Plugin architecture
  • Class registries

9. __getattr__ and __getattribute__

These let you intercept attribute access:

class A:
def __getattribute__(self, name):
print(f"Looking for {name}")
return super().__getattribute__(name)

print(A().some_attr) # Triggers the message

__getattr__ only fires for missing attributes:

class A:
def __getattr__(self, name):
return f"{name} not found — using fallback"

Use Cases

  • Lazy attribute loading
  • API fallback strategies
  • Debugging or logging attribute access

10. Dynamic Class Creation

MyClass = type("MyClass", (), {"x": 42})
print(MyClass().x) # Output: 42

The type() function can be used to define new classes on the fly.

Use Cases

  • Runtime model creation (e.g., in ORMs)
  • Dynamic plugin systems
  • Serialization frameworks

11. Operator Overloading

class Num:
def __init__(self, value): self.value = value
def __add__(self, other): return Num(self.value + other.value)
def __repr__(self): return f"Num({self.value})"

print(Num(5) + Num(3)) # Output: Num(8)

Python lets you override operators with magic methods like __add__, __sub__, etc.

Use Cases

  • DSLs (Domain Specific Languages)
  • Symbolic math (e.g., SymPy)
  • Machine learning libraries (e.g., TensorFlow, PyTorch)

12. Self-Defining Functions

def f():
print("First time")
global f
f = lambda: print("Now I do something else")

f() # First time
f() # Now I do something else

Use Cases

  • Lazy initialization
  • Bootstrapping code
  • Performance optimization

Final Thoughts

You probably won’t use these Python tricks every day, but knowing them puts you in a league beyond the average programmer. These techniques can help you write more expressive code, debug smarter, or even land that dream job.

Remember: Python is only as flexible as your curiosity allows. So, the next time someone asks, “How flexible are you?”—say “I’m as flexible as a Python,” and then show them exactly what that means.

Comments are closed

Related Posts