20 cool things you can do with #Python's built-in functions 🐍🧵
1. Make a dictionary from two lists:
2. Get a counter when looping through a sequence:
3. Check if a condition holds true for any or all items in a sequence:
4. Print things:
5. Summing values:
6. Uniquify a list:
7. Reverse a list:
8. Make a range of integers with a step:
9. Get a quotient and remainder, for example to divide seconds into minutes + seconds:
10. Name and apply a slice:
11. Use dir() together with a list comprehension to only list "public" methods (and attributes) of an object:
12. Get the min and max of a sequence:
13. Get user input:
14. Check for, get and set attributes:
15. Call a method on the parent class:
16. Use next() to retrieve the next value from a generator:
17. Make values absolute:
18. Sort values, by key, reversed, and in-place:
19. Round numbers:
20. See the representation / string of an object:
Python docs:
docs.python.org/3/library/func…

@PyBites YouTube training:

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Bob Belderbos | @bbelderbos@fosstodon.org

Bob Belderbos | @bbelderbos@fosstodon.org Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @bbelderbos

Feb 2
Stop scattering `if/elif` checks across your code to manage workflow states.

If your feature has a real lifecycle (draft → review → approved → published), model it as a **state machine**. Image
With `transitions`, you attach the machine to your existing object (`model=content`) and it injects the trigger methods + keeps a `state` field for you.
What you get:

* Triggers become methods (`submit()`, `approve()`, `publish()`)
* Invalid moves fail fast (`MachineError`)
* Workflow rules live in one place (self-documenting), not across views/templates/services
Read 6 tweets
Jan 29
"The borrow checker is fighting me!" 🥊

No, it's not. It's saving you from a 3 AM debugging session three months from now.

In Python, variables are references. You pass an object around, everyone shares it.

In Rust, by default, Ownership is exclusive. Image
Why? Because if `s1` and `s2` both "owned" the memory, they would both try to free it when they go out of scope. -> Double Free Error. -> Security Vulnerability.
Rust forces you to address this before runtime and be explicit:
1. Move it (give it away)
2. Clone it (make a copy)
3. Borrow it (`&s1` - look but don't touch)
Read 4 tweets
Jan 23
You don’t learn by watching. You learn by breaking things. 💡

We've spoken with developers who’d watched multiple 10+ hour Udemy courses.

They knew the theory: Django, Docker, AsyncIO. Image
But when I asked them to:
• spin up a simple CLI tool from scratch, or
• deploy a small app to the cloud…

They froze.

“I usually just follow the video.”

That’s tutorial hell.

It feels productive, but you’re borrowing someone else’s problem-solving.
The way out is simple (not easy): build something with no guide.
• You will get stuck.
• You will read docs.
• You will use AI (deliberately).
• You will feel frustrated.
• You will learn for real.

That’s why we teach around projects, not lectures. 💪
Read 7 tweets
Aug 24, 2023
🚀 10 useful things you can do more easily with pathlib than os in #Python ...

Check out this thread to see how to write more readable, simple and beautiful code with `pathlib` ...
1️⃣ Creating/Joining Paths:

os:
p = os.path.join('folder', 'file.txt')

pathlib:
p = Path('folder') / "file.txt"
2️⃣ Getting Home Dir:

os:
home = os.path.expanduser("~")

pathlib:
home = Path.home()
Read 13 tweets
Aug 24, 2023
Customizing Class Creation with __init_subclass__ 💡

In #Python, the __init_subclass__() method is a powerful and lesser-known tool for customizing class creation behavior in subclasses.

Example: class Plugin:     plugins = []      def __init_subclass__(cls, **kwargs):         super().__init_subclass__(**kwargs)         cls.plugins.append(cls)  class ConcretePlugin(Plugin):     pass  class AnotherPlugin(Plugin):     pass  print(Plugin.plugins)   # Output: [<class '__main__.ConcretePlugin'>, <class '__main__.AnotherPlugin'>]
In the provided code:

📘 Plugin is a base class.

🚀 Whenever a subclass of Plugin is defined, __init_subclass__ of Plugin is automatically called.

🔍 Inside the __init_subclass__ method, the newly defined subclass (cls in this context) is appended to the plugins list.
✅ So, after defining the ConcretePlugin and AnotherPlugin subclasses, the plugins list contains references to these two classes.

This technique can be useful to enforce certain constraints, add class-level attributes, or perform any setup tasks 💡 💪
Read 5 tweets
Apr 13, 2022
When you build up a #Python string use a list over string concatenation (+=).

See stackoverflow.com/a/3055541:
> Strings are immutable and can't be changed in place. To alter one, a new representation needs to be created.

So that happens repeatedly here = slower.
Btw instead of loop + append, I could also have used a list comprehension inside the .join()
Also this probably only becomes a problem for bigger data. I post it here for awareness, but writing readable / maintainable code should be your first focus.
Read 4 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us!

:(