Advertisement · 728 × 90
#
Hashtag
#DailyPythonTip
Advertisement · 728 × 90

Python Tip #88 (of 365):

When assigning multiple variables to the same initial immutable value, use multiple assignment

Instead of this:

x = 0
y = 0

You can do this:

x = y = 0

That's safe as long as the value is immutable (numbers, strings, booleans, or None).

#Python #DailyPythonTip

5 0 1 0

Python Tip #87 (of 365):

Use tuple unpacking to swap references 🧵

You can use tuple unpacking to swap the values of 2 variables in #Python:

x, y = y, x

Outside of feeling clever in an interview, you may NEVER need to do that... but you MIGHT need to do something similar.

#DailyPythonTip

4 0 1 0

Python Tip #86 (of 365):

Acknowledge that containment is (sort of) a lie. 🧵

Data structures in Python don't contain data...

Well, at least data structures don't contain objects.

#Python #DailyPythonTip

4 0 1 0

Python Tip #85 (of 365):

Think of variables as pointers. 🧵

When explaining your code in Python, be sure to disambiguate between the 2 types of change (assignments and mutations).

#Python #DailyPythonTip

3 0 1 0

Python Tip #84 (of 365):

Use variables to improve code clarity. 🧵

Today's tip is the inverse of yesterday's tip.

Well-named variables CAN make your code more readable and they don't really make your code less efficient (after all, variables are just pointers).

#Python #DailyPythonTip

8 0 1 0

Python Tip #83 (of 365):

Don't overuse variables in Python. 🧵

Expressions are valid almost anywhere in Python.

If a variable isn't needed to refer to a value multiple times AND the variable isn't clearer than the expression it replaces, just use the expression instead.

#Python #DailyPythonTip

4 0 1 0
Preview
Variables are pointers in Python Python's variables are not buckets that contain objects; they're pointers. Assignment statements don't copy: they point a variable to a value (and multiple variables can "point" to the same value).

Python Tip #82 (of 365):

Don't assign 2 variables to the same mutable object. 🧵

An assignment of one variable to another ("x = y") is usually only a good idea for IMMUTABLE VALUES.

#Python #DailyPythonTip

3 0 1 0

Python Tip #81 (of 365):

Normalize cases with the string casefold method. 🧵

When normalizing the cases of strings for the sake of a comparison, consider using casefold instead of lower or upper.

#Python #DailyPythonTip

4 0 1 0

Python Tip #80 (of 365):

Concatenate iterables with the string join method. 🧵

Instead of this:

guests = ""
for name in names:
if guests:
guests += ", "
guests += name

Do this:

guests = ", ".join(names)

#Python #DailyPythonTip

3 0 1 0

Python Tip #79 (of 365):

Don't use strip if you just need to remove a single character 🧵

To remove a single trailing newline, instead of using rstrip:
line = line.rstrip("\n")

Consider using removesuffix:
line = line.removesuffix("\n")

#Python #DailyPythonTip

3 0 1 0

Python Tip #78 (of 365):

Don't remove string prefixes and suffixes manually. 🧵

Instead of this:

normalized = hex_value.lower()
if normalized.startswith("0x"):
normalized = normalized[2:]

Do this:

normalized = hex_value.lower().removeprefix("0x")

#Python #DailyPythonTip

15 1 2 1

Python Tip #77 (of 365):

Need to check for the presence of prefixes or suffixes? Use startswith or endswith. 🧵

Instead of this:
test_key = (API_KEY[:5] == "test-")

Do this:
test_key = API_KEY.startswith("test-")

#Python #DailyPythonTip

3 0 1 0

Python Tip #76 (of 365):

Don't call the string split() method with a space character 🧵

Instead of this:

words = some_string.split(" ")

Do this:

words = some_string.split()

#Python #DailyPythonTip

4 0 1 0
Preview
Why splitlines() instead of split("\n")? To split text into lines in Python, use the splitlines() method, not the split() method.

Python Tip #75 (of 365):

Don't use the string split() method for splitting lines.

Instead of this:
lines = poem.split("\n")

Do this:
lines = poem.splitlines()

The string splitlines method will:
• Trim a trailing newline (if there is one)
• Split by "\r\n", "\n", or "\r"

#Python #DailyPythonTip

6 0 1 0

Python Tip #74 (of 365):

Print blank lines with print()

Instead of this:
print("TITLE\n")
print("Descrption")

Consider this:
print("TITLE")
print()
print("Descrption")

It's easier to see there's meant to be a blank line when a separate print call is used.

#Python #DailyPythonTip

2 0 1 0

Python Tip #73 (of 365):

Use self-concatenation to make horizontal rules

To print 80 '=', '-', or '*' characters, you can multiply a single-character string by the number 80:

print("-" * 80)

#Python #DailyPythonTip

5 0 0 2

Python Tip #72 (of 365):

You can redirect all printed output in Python with contextlib.redirect_stdout 🧵

from contextlib import redirect_stdout
import io

with redirect_stdout(io.StringIO()) as output:
print("hello")

printed_text = output.getvalue()

#Python #DailyPythonTip

2 0 1 0

Python Tip #71 (of 365):

Print non-standard output to standard error 🧵

Python's print function writes to the "standard output" stream by default.

But terminals have a second output stream that also writes to the screen: standard error.

#Python #DailyPythonTip

3 0 2 0

Python Tip #70 (of 365):

Print partial lines by specifying end="" 🧵

Instead of writing to "sys.stdout" to avoid printing newlines:

sys.stdout.write(prefix)
sys.stdout.write(remainder + "\n")

Consider passing end to print():

print(prefix, end="")
print(remainder)

#Python #DailyPythonTip

3 0 0 0

Python Tip #69 (of 365):

Joining and then printing? Consider using print() to do your joining instead. 🧵

print() can often function as an alternative to the string join method.

#Python #DailyPythonTip

3 0 1 0

Python Tip #68 (of 365):

Instead of printing an f-string with a single space between values, consider passing 2 arguments to print.

Instead of this:

print(f"User: {name}")

You could do this:

print("User:", name)

Why?

Less syntax. That's all.

#Python #DailyPythonTip

1 0 0 0

Python Tip #67 (of 365):

When making a class that should support inheritance, don't hard-code references to your own class. 🧵

If your class is meant to be inherited from, instead of hard-coding references to it, use type(self) to dynamically look up the current class.

#Python #DailyPythonTip

3 0 1 0

Python Tip #66 (of 365):

Consider implementing __eq__ on every class you make 🧵

Tips 63 and 64 were about always implementing __init__ and __repr__ methods on your classes.

You don't ALWAYS need a __eq__ method, but you should seriously consider one.

#Python #DailyPythonTip

4 0 1 0

Python Tip #65 (of 365):

Rarely define a __str__ method 🧵

A __str__ method controls the human-readable string representation of your class instances.

You may think you need __str__, but most classes really don't need this method and your class probably doesn't either.

#Python #DailyPythonTip

2 0 1 0

Python Tip #64 (of 365):

Ensure your classes all have a sensible __repr__ method 🧵

A __repr__ method controls the default string representation of your class instances.

Pretty much every object should have a nice string representation.

#Python #DailyPythonTip

4 0 1 0

Python Tip #63 (of 365):

Every class should have an initializer 🧵

If your class doesn't have an initializer method, it could probably be a module instead of a class.

#Python #DailyPythonTip

4 0 1 0

Python Tip #62 (of 365):

Avoid conditionally present attributes 🧵

Python's "del" statement is pretty much ONLY used to delete dictionary keys (or list indexes).

You'll probably never see "del" used to delete an attribute. There's a reason for that.

#Python #DailyPythonTip

3 0 1 0

Python Tip #61 (of 365):

When passing the same object(s) to different functions, consider a class. 🧵

Consider this code:

server = get_connection(host, name, password)
messages = [
get_message(server, u)
for u in get_message_uids(server)
]
close_connection(server)

#Python #DailyPythonTip

6 0 1 0

Python Tip #60 (of 365):

Be cautious of "if" expressions in comprehensions 🧵

An "if" expression in a "for" loop can look confusing:

sanitized = [n if n > 0 else 0 for n in counts]

That "else" isn't part of the comprehension. It's just inline "if" expression.

#Python #DailyPythonTip

3 0 1 0

Python Tip #59 (of 365):

Don't use comprehensions to loop 🧵

List comprehensions are for creating new lists, not for looping.

This is a valid comprehension:

[print(n**2) for n in numbers]

But it's also a misuse of the comprehension syntax.

#Python #DailyPythonTip

4 0 1 0