Trey Hunner Profile picture
Python team trainer 🎓 Creating ah-ha moments in #Python with @PythonMorsels🐍🍪 Thought follower 💭 #pythonoddity tweeter 🤔 @treyhunner@mastodon.social he/him
Aromat Profile picture Matthew Kane Profile picture Niels Rikze Profile picture Learning in Public - Coding - DataSci Profile picture 4 subscribed
Mar 14, 2023 4 tweets 2 min read
Instead of getter and setter methods, in #Python we often use a property to control what happens when we get/set a specific attribute.

>>> r = Rectangle(5, 4)

With a property, instead of this:

>>> r.get_area()
20
>>> r.set_area(8)

We can do this:

>>> r.area
20
>>> r.area = 8 Image You can think of a property as a virtual attribute.

Accessing a property runs a function. And so does assigning to a property!

Don't believe me? Try running this and take a look at what's printed.

pym.dev/p/2krm5/
Mar 10, 2023 6 tweets 3 min read
In Python we don't have "main" functions.

Instead we ask the question "is my module the entry point to this #Python process?"

We do that with this very strange looking condition:

if __name__ == "__main__":
main() Why does this work? 🤔

Well, each module has a __name__ variable in it which represents the name of that module. There's also __file__, which is its file path and __doc__ which is its docstring.

But when Python runs a module as a script, it does something different...
Mar 9, 2023 5 tweets 1 min read
There are 3 methods I implement on most #Python classes I make.

• __init__: the initializer method
• __repr__: the programmer-readable string representation
• __eq__: implement a nice sense of equality (what the == operator does)

__init__ & __repr__ always, __eq__ usually If you're inheriting from another class you'll likely get some (or all) of those for free.

But if you're creating your own class, it's easy to overlook __repr__ and even easier to overlook __eq__.

But both of those methods can make it easier to work with your class instances.
Mar 8, 2023 4 tweets 1 min read
Need to de-duplicate items in a list?

>>> my_items = ["duck", "mouse", "duck", "computer"]

This works if you don't care about the order:

>>> unique_items = set(my_items)

If maintaining item order is important, this works:

>>> unique_items = list(dict.fromkeys(my_items)) Confused by list(dict.fromkeys(...))?

dict.fromkeys() accepts an iterable and creates a new dictionary with the iterable items as keys and None as the values.

list() accepts an iterable and creates a new list from its items

When you loop over a dictionary you get just the keys
Oct 3, 2022 5 tweets 3 min read
Need the largest item in an iterable in #Python? 🎚️

>>> max(iterable)

Need the largest n items in an iterable? ⬆️

>>> from heapq import nlargest
>>> nlargest(n, iterable)

Need all items arranged from largest to smallest? 📉

>>> sorted(iterable, reverse=True) Need the smallest item in a #Python iterable? ⚖️

>>> min(iterable)

Need the n smallest items? ⬇️

>>> from heapq import nsmallest
>>> smallest(n, iterable)

If you need all of them in increasing order, use sorted (no reverse) 📈

>>> sorted(iterable)
Sep 7, 2022 4 tweets 1 min read
Python's "for" loops can only loop in one direction: forwards!

If you need to loop in the reverse direction, the built-in "reversed" function can help.

>>> colors = ["pink", "blue", "green"]
>>> for color in reversed(colors):
... print(color)
...
green
blue
pink The "reversed" function only works on reversible iterables.

Fortunately, most of the iterables you might care to reverse *are* reversible.

Sequences (e.g. lists, tuples, and strings) are reversible and so are dictionaries (as of Python 3.8).
Sep 6, 2022 7 tweets 4 min read
Python class curious? 🤔

Here's a 4-in-1 thread about class-related Python terms 🐍

• class
• class instance
• method
• initializer method

Make sure to click through to each of the 4 thread for more 🧵

#Python #TerminologyTuesday A class is essentially a template for creating an object in Python.

Every object has a class, seen by the "type" function:

>>> type(4)
<class 'int'>

The terms "type" & "class" are synonyms in Python.

Some "functions" are actually implemented as classes.

On 𝗰𝗹𝗮𝘀𝘀𝗲𝘀 🖱️
Aug 30, 2022 14 tweets 4 min read
What's "assignment" in #Python?

This might seem like a simple concept, but there are some gotchas in the way assignment works in Python.

Fundamentally "assignment" describes the action of binding a name to a value. You can assign a variable (a.k.a. name) to a value (a.k.a. object) with an "assignment statement".

That uses an = sign, like this:

>>> x = []

That assigns the name x to an empty list.

If "x" already exists, an = sign will re-assign it to a new value:

.>>> x = 4
>>> x
4
Aug 29, 2022 5 tweets 2 min read
Python's strings have 47 methods!

But these 12 string methods are the only ones really worth committing to memory for most Python programmers:

join
split
replace
strip
casefold
startswith
endswith
splitlines
format
count
removeprefix
removesuffix A table showing the 12 stri... But what about find, encode, translate, isnumeric, and all the other string methods?

While there are other useful string methods, most of the remaining methods have a niche use case or have quirks that make them tricky to use.

For example the title method has quirks 👇
Aug 23, 2022 21 tweets 9 min read
What's a "generator" in Python?

#TerminologyTuesday time ⏰

Let's discuss:
• The main reason generators are used
• The 2 ways to make a generator
• Lesser known generator features
• Why and when to use generators

Thread 🧵👇 Generators are typically used as lazy iterables.

By "lazy" I mean that they don't actually compute their values until they absolutely need to.

Essentially generators will "generate" their next value as soon as they're asked for it.
Aug 9, 2022 17 tweets 4 min read
What's a regular expression (a.k.a. regex)? 🤔 #TerminologyTuesday

Yes, they're a programming language within a programming language that's just for pattern matching and they're extremely succinct.

But what does "regular expression" really mean? And where did they come from? Haven't seen regular expressions?

Imagine a special purpose programming language where every single character is a statement and no whitespace or comments are allowed. 😨

Regular expressions are extremely information dense but very helpful for certain types of pattern matching.
Aug 3, 2022 8 tweets 3 min read
I usually recommend the "literal" list & dict syntax in #Python over the built-in list & dict functions.

✅ []
🚫 list()

✅ {}
🚫 dict()

✅ {"name": "Trey", "id": 4}
🚫 dict(name='Trey', id=4)

So what's the purpose of list(...) and dict(...)? 🤔

Copying!

(thread🧵) Per the Zen of Python:

> there should be one— and preferably only one —obvious way to do it

I see [] and {} as "the one obvious" way to make a new list/dict.

[] and {} are even more common than list() and dict() so are likely more obvious to most Python devs.
Aug 2, 2022 8 tweets 3 min read
What's an "object" in Python?

According to the Python glossary, an object is:

> Any data with state (attributes or value) and defined behavior (methods). Also the ultimate base class of any new-style class.

What does that really mean? (thread🧵)

#Python #TerminologyTuesday Usually when we think of an "object" we think of class instance. For example these are all objects:

>>> numbers = [2, 1, 3, 4, 7] # a list object
>>> colors = {"red", "green", "blue", "yellow"} # a set object
>>> name = "Trey" # a string object
>>> n = 3 # an int object
Aug 1, 2022 8 tweets 2 min read
Need to remove all spaces from a string in #Python? 🌌🐍

Let's take a quick look at:

• removing just space characters
• removing all whitespace
• collapsing consecutive whitespace to 1 space
• removing from the beginning/end
• removing from the ends of every line

Thread🧵 If you just need to remove space characters you could use the string replace method to replace all spaces by an empty string:

>>> greeting = " Hello world! "
>>> greeting.replace(" ", "")
'Helloworld!'

But you may also want to remove other whitespace too (e.g. newlines)...
Jul 19, 2022 11 tweets 5 min read
class: a template for creating an object

We've defined instance and method. For this week's #TerminologyTuesday, it's finally time to define the word "class" in #Python. 📕🐍

Where do classes come up and how do they work? 🤔 The terms "class" and "type" are synonyms in Python.

The type of an object is its class and an object's class is a "type".

As we discussed when we defined "class instance" last week, every object in Python has a class. That means classes are EVERYWHERE in Python.
Jul 12, 2022 13 tweets 5 min read
instantiate (verb): to make an "instance" of a class

Okay... but what's an "instance"? 🤔

instance (noun): an object

Wait, that's not a helpful definition.

Let's talk about class instances and class instantiation in Python.
#TerminologyTuesday You can think of a "class" as a blueprint for making an objects that have specific functionality and contain particular types of data. 📘

list is a class in #Python

>>> list
<class 'list'>

An "instance of the list class" could also be called a "list object" or just "a list".
Jul 11, 2022 6 tweets 2 min read
"Why does Python have a datetime.timedelta object?"

My Intro to #Python students sometimes ask me that question ☝

My answer:

1. Moments in time are not the same as durations of time
2. Sometimes an idea is important enough to warrant a new data type

Let me explain 🧵 First, let's note that datetime != timedelta

These represent moments in time:

>>> nye = datetime(2022, 12, 31)
>>> halloween = datetime(2022, 10, 31)

But this is a *duration* of time:

>>> nye - halloween
datetime.timedelta(days=61)

A datetime can't represent "61 days"
Jun 1, 2022 9 tweets 2 min read
Need to split up seconds into hours, minutes, & seconds in #Python?

This is one of the rare instances in which I might reach for Python's built-in divmod function. Though datetime.timedelta might work too, depending on your use case.

Let's compare int, //, divmod, & timedelta🧵 Given a number of seconds:

>>> duration = 4542

You might have thought to use division, modulo, and Python's int function 🤔

hours = int(duration/60 / 60)
minutes = int(duration/60 % 60)
seconds = duration % 60
May 31, 2022 11 tweets 5 min read
Another fundamental Python term for #TerminologyTuesday

callable: an object which can be called

The classical "callable" is a function, but in #Python classes are also callables. In many programming languages (e.g. JS, PHP, C++) creating a new "instance" of a class (an object whose type is that class) involves the "new" keyword:

let eol = new Date(2020, 1, 1);

But in #Python to make a new class instance we just call the class:

eol = date(2020, 1, 1)
May 31, 2022 4 tweets 1 min read
Python Quiz: what input will result in different behavior from the built-in int function and the math.floor function?

>>> int(x)
vs

>>> import math
>>> math.floor(x)

They're *usually* the same Those replying negative numbers: you're absolutely right!

There's another input that has different behavior for math.floor and int in Python too. 🤔

Other guesses?
May 26, 2022 12 tweets 4 min read
Python's "for" loops are single-purposed: they can loop over an iterable item-by-item. That's it.

The "for" loop itself can't loop in reverse or loop over multiple iterables.

For this reason, looping helpers are a VERY big deal in #Python.

Let's talk about looping helpers. 🧵 Want to loop over an iterable in the reverse direction? If it's a reversible iterable (lists, tuples, dictionaries, etc), you can use the reversed helper:

>>> colors = ["pink", "blue", "green"]
>>> for color in reversed(colors):
... print(color)
...
green
blue
pink