Python Operators & Booleans

Python Tutorial › Basics › Operators & Booleans

Python Operators & Booleans

BeginnerLesson 12 of 4712 min read12 runnable examples

Operators are the symbols that do the work in an expression: they add numbers, compare values and combine conditions. This lesson covers all seven groups of Python operators and the booleans they produce.

In this lesson
  • Arithmetic and assignment operators
  • Comparison operators and chaining
  • and, or, not with short-circuiting
  • is vs == and the in operator

Arithmetic operators

Python
a, b = 14, 4print(a + b, a - b, a * b)print(a / b, a // b, a % b, a ** 2)
Output
18 10 56
3.5 3 2 196

+ and * also work on strings and lists:

Python
print("ab" + "cd", "-" * 10)print([1, 2] + [3], [0] * 3)
Output
abcd ----------
[1, 2, 3] [0, 0, 0]

The Numbers & Math lesson explains //, % and rounding in detail.

Assignment operators

Augmented assignment updates a variable using its current value.

OperatorSame as
x += 3x = x + 3
x -= 3x = x - 3
x *= 3x = x * 3
x /= 3x = x / 3
x //= 3x = x // 3
x %= 3x = x % 3
x **= 3x = x ** 3
Python
balance = 1000balance -= 250      # withdrawalbalance *= 1.05     # 5% interestprint(balance)
Output
787.5

Comparison operators

Comparisons return a boolean: True or False.

OperatorMeaning
==equal
!=not equal
> / <greater than / less than
>= / <=greater or equal / less or equal
Python
score = 72print(score == 72, score != 72)print(score > 50, score <= 60)print("apple" < "banana")     # strings compare alphabeticallyprint(10 == 10.0)             # int and float with the same value are equal
Output
True False
True False
True
True

Python lets you chain comparisons, just like in maths:

Python
age = 25print(18 <= age < 60)
Output
True

Logical operators: and, or, not

ExpressionTrue when
a and bboth are true
a or bat least one is true
not aa is false
Python
has_ticket = Trueis_adult = Falseprint(has_ticket and is_adult)print(has_ticket or is_adult)print(not is_adult)
Output
False
True
True

Short-circuiting

and stops at the first falsy value and or stops at the first truthy value. They return that value itself, not always True/False. This gives two handy idioms:

Python
name = ""display = name or "Guest"          # default when name is emptyprint(display) items = []print(len(items) > 0 and items[0])  # items[0] is never evaluated
Output
Guest
False

Booleans and truthiness

True and False are the two boolean values, and bool is a subclass of int. In an if or while, any value is treated as true or false:

Python
print(True + True, True * 10)for value in [0, 3, "", "text", [], [1], None]:    print(repr(value), "->", "truthy" if value else "falsy")
Output
2 10
0 -> falsy
3 -> truthy
'' -> falsy
'text' -> truthy
[] -> falsy
[1] -> truthy
None -> falsy

Identity operators: is, is not

== asks “do these have the same value?” is asks “are these the very same object?”

Python
a = [1, 2]b = [1, 2]c = aprint(a == b, a is b)print(a is c)
Output
True False
True
Tip

Use is only to compare with None, True or False: if result is None:. For everything else use ==.

Membership operators: in, not in

Python
roles = ["admin", "tester", "viewer"]print("tester" in roles)print("guest" not in roles)print("py" in "python")                  # substring checkprint("id" in {"id": 7, "name": "x"})   # checks dict keys
Output
True
True
True
True

Bitwise operators

Bitwise operators work on the binary digits of integers. You will meet them in permissions, flags and low-level code.

Python
a, b = 6, 3       # 110 and 011 in binaryprint(a & b, a | b, a ^ b)print(~a, a << 1, a >> 1)
Output
2 7 5
-7 12 3

Operator precedence

From highest to lowest (operators on the same row are evaluated left to right, except **):

PrecedenceOperators
1() parentheses
2**
3+x, -x, ~x
4*, /, //, %
5+, -
6bitwise: << and >>, then &, then ^, then bitwise OR
7comparisons, in, not in, is, is not
8not
9and
10or
Python
print(True or False and False)    # and binds tighter: True or (False and False)print(not 1 == 2)                 # not (1 == 2)
Output
True
True

Check your understanding

Predict the output

x = 5print(x > 3 and x < 10, x > 3 or 1 / 0, 0 or "" or "last")

Quick quiz

1. What does 10 != 10.0 return?

2. What does "" or "default" return?

3. Which checks whether x is None?

4. What does 1 < 3 < 2 evaluate to?

Exercise: leap year check

A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. Print each year with True or False.

Input
1900, 2000, 2024, 2026
Expected output
1900 False
2000 True
2024 True
2026 False
Hint 1

Combine % with and and or.

Hint 2

(year % 4 == 0 and year % 100 != 0) or year % 400 == 0

Program Practice

Python operators FAQ

What is the difference between == and is in Python?

== compares values; is compares identity (whether two names refer to the same object). Two separate lists with the same items are == but not is.

Does Python have && and || operators?

No. Python uses the words and, or and not.

Does Python have ++ and — operators?

No. Use x += 1 and x -= 1.

What does the % operator do in Python?

It returns the remainder of a division (17 % 5 is 2). It is also used in old-style string formatting such as "%d items" % 3.

Python Type Casting

Python Tutorial › Basics › Type Casting

Python Type Casting

BeginnerLesson 11 of 479 min read8 runnable examples

Type casting means converting a value from one type to another, such as turning the text “42” from input() into the number 42. Python does some conversions for you, and you do the rest with built-in functions named after the types.

In this lesson
  • Implicit vs explicit conversion
  • Convert between numbers and strings
  • Convert between collections
  • Handle values that cannot be converted

Implicit conversion

When you mix an int and a float in arithmetic, Python converts the int to a float for you, so no precision is lost:

Python
qty = 3          # intprice = 19.5     # floattotal = qty * priceprint(total, type(total).__name__)print(True + True)    # bool is a kind of int: True is 1
Output
58.5 float
2

Python will not guess between text and numbers. Mixing them is an error:

Python
age = 30print("Age: " + age)
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print("Age: " + age)
          ~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str

Explicit conversion functions

FunctionConverts toExampleResult
int(x)whole numberint("42"), int(9.8)42, 9
float(x)decimalfloat("3.5"), float(2)3.5, 2.0
str(x)textstr(100)'100'
bool(x)True/Falsebool(0), bool("no")False, True
list(x)listlist("abc")['a', 'b', 'c']
tuple(x)tupletuple([1, 2])(1, 2)
set(x)setset([1, 1, 2]){1, 2}
dict(x)dictdict([("a", 1)]){'a': 1}

Numbers and strings

Python
age = 30print("Age: " + str(age))        # number to textprint(int("42") + 8)             # text to numberprint(float("3.75") * 2)print(int(9.99), int(-9.99))     # int() truncates towards zeroprint(int("  15\n"))             # surrounding whitespace is ignored
Output
Age: 30
50
7.5
9 -9
15

int() can also read numbers written in other bases:

Python
print(int("ff", 16), int("0b1010", 0), int("777", 8))
Output
255 10 511

Values that cannot be converted

Python
print(int("3.5"))
Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(int("3.5"))
          ~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '3.5'

int() will not read a decimal string. Convert to float first, or catch the error:

Python
print(int(float("3.5"))) for text in ["12", "4.0", "abc"]:    try:        print(text, "->", int(text))    except ValueError:        print(text, "-> not a whole number")
Output
3
12 -> 12
4.0 -> not a whole number
abc -> not a whole number

Converting to bool

bool() returns False for “empty” or zero values and True for everything else.

Python
for v in [0, 0.0, "", "0", "False", [], [0], None]:    print(f"{v!r:8} -> {bool(v)}")
Output
0        -> False
0.0      -> False
''       -> False
'0'      -> True
'False'  -> True
[]       -> False
[0]      -> True
None     -> False
Watch out

bool("False") is True, because it is a non-empty string. To read a yes/no answer, compare the text: answer.strip().lower() in ("yes", "y", "true").

Between collections

Python
letters = list("banana")print(letters)print(set(letters))                    # duplicates removedprint(tuple(letters[:3]))print("".join(letters))               # list of strings back to one string pairs = [("chrome", 120), ("firefox", 118)]print(dict(pairs))print(list({"x": 1, "y": 2}))          # a dict converts to its keys
Output
['b', 'a', 'n', 'a', 'n', 'a']
{'a', 'b', 'n'}
('b', 'a', 'n')
banana
{'chrome': 120, 'firefox': 118}
['x', 'y']

Check your understanding

Predict the output

print(int("7") + float("2.5"), str(7) + str(2.5), int(True))

Quick quiz

1. What does int("3.9") do?

2. What does bool("0") return?

3. Which converts [3, 1, 3] to a collection with only unique items?

Exercise: sum numbers from text

A line of comma-separated numbers arrives as text. Convert it and print the total and the average.

Input
"12, 7.5, 30, 0.5"
Expected output
[12.0, 7.5, 30.0, 0.5]
Total: 50.0
Average: 12.5
Hint 1

split(",") gives the parts as strings; float() converts each one.

Program Practice

Python type casting FAQ

How do I convert a string to an integer in Python?

Use int("42"). If the string may contain a decimal point, use int(float(text)), and wrap it in try / except ValueError for user input.

How do I convert an integer to a string?

Use str(42), or put it in an f-string: f"{42}".

What is the difference between implicit and explicit type conversion?

Implicit conversion is done by Python automatically, such as int to float in 3 * 1.5. Explicit conversion is when you call a function such as int() or str() yourself.

How do I convert a list to a string?

Use ", ".join(items) for a list of strings. For other values, convert each one first: ", ".join(map(str, numbers)).

Python Numbers & Math

Python Tutorial › Basics › Numbers & Math

Python Numbers & Math

BeginnerLesson 10 of 4711 min read12 runnable examples

Python has three number types and a rich set of tools for working with them. This lesson covers arithmetic, rounding, the float precision trap, the math module and random numbers.

In this lesson
  • int, float and complex numbers
  • Arithmetic including // and %
  • Rounding and float precision
  • The math and random modules

Three number types

Python
count = 42          # int: whole number, any sizeratio = 0.75        # float: decimal numbersignal = 3 + 4j     # complex: real + imaginary part print(type(count).__name__, type(ratio).__name__, type(signal).__name__)print(abs(signal))  # length of the complex number
Output
int float complex
5.0

Large numbers are easier to read with underscores. Python ignores them:

Python
population = 1_428_627_663print(population)print(2 ** 64)
Output
1428627663
18446744073709551616

Arithmetic operators

OperatorMeaning17 ? 5
+add22
-subtract12
*multiply85
/divide (always float)3.4
//floor divide (round down)3
%remainder (modulo)2
**power1419857
Python
a, b = 17, 5print(a + b, a - b, a * b)print(a / b, a // b, a % b)print(a ** b)
Output
22 12 85
3.4 3 2
1419857

// and % work as a pair: a == (a // b) * b + a % b. divmod() gives both at once. A classic use is converting seconds:

Python
seconds = 3725minutes, secs = divmod(seconds, 60)hours, minutes = divmod(minutes, 60)print(f"{hours}h {minutes}m {secs}s")
Output
1h 2m 5s
Tip

n % 2 == 0 is the standard test for an even number. Many practice programs use it.

Order of operations

Python follows the usual maths rules: * first, then , /, //, %, then + and -. Use parentheses to make your intent clear.

Python
print(2 + 3 * 4)print((2 + 3) * 4)print(2 ** 3 ** 2)    # ** groups from the right: 2 ** 9print(-2 ** 2)        # ** binds tighter than the minus sign
Output
14
20
512
-4

Rounding

Python
price = 2.675print(round(price, 2))print(round(2.5), round(3.5))     # ties round to the even numberprint(int(7.9), int(-7.9))        # int() cuts off the decimals
Output
2.67
2 4
7 -7

round(2.5) gives 2 because Python uses “banker’s rounding”: a tie goes to the nearest even number. round(2.675, 2) gives 2.67 because 2.675 cannot be stored exactly as a float; it is really slightly less.

Float precision

Python
print(0.1 + 0.2)print(0.1 + 0.2 == 0.3) import mathprint(math.isclose(0.1 + 0.2, 0.3))
Output
0.30000000000000004
False
True

For money, use Decimal with string inputs, which stores decimal digits exactly:

Python
from decimal import Decimal print(Decimal("0.1") + Decimal("0.2"))total = Decimal("19.99") * 3print(total)
Output
0.3
59.97
Watch out

Never compare floats with ==. Use math.isclose() or compare rounded values.

Useful built-in functions

Python
nums = [4, -9, 15, 2]print(abs(-9), max(nums), min(nums), sum(nums))print(pow(2, 10), pow(2, 10, 1000))   # third argument: remainder
Output
9 15 -9 12
1024 24

The math module

Python
import math print(math.sqrt(144))print(math.floor(4.7), math.ceil(4.2))print(math.pi)print(math.factorial(5))print(math.gcd(48, 36), math.lcm(4, 6))print(round(math.log10(1000)), round(math.hypot(3, 4)))
Output
12.0
4 5
3.141592653589793
120
12 12
3 5

Random numbers

The random module picks pseudo-random values. random.seed() makes the sequence repeatable, which is useful in tests.

Python
import random random.seed(7)print(random.randint(1, 6))           # dice roll: 1 to 6 inclusiveprint(random.choice(["red", "green", "blue"]))print(round(random.random(), 3))      # float from 0.0 up to 1.0
Output
3
red
0.395

Number systems

Python
print(bin(10), oct(10), hex(255))print(int("1010", 2), int("ff", 16))
Output
0b1010 0o12 0xff
10 255

Check your understanding

Predict the output

print(7 // 2, -7 // 2, 7 % 3, -7 % 3)

Quick quiz

1. What does 10 / 2 return?

2. What does round(2.5) return?

3. How do you get the remainder of 17 divided by 5?

4. Which is the safe way to compare two floats?

Exercise: simple interest

Calculate simple interest and the total amount, rounded to 2 decimals.

Input
principal = 15000, rate = 7.5 (% per year), years = 3
Expected output
Interest: 3375.0
Total: 18375.0
Hint 1

Simple interest is principal * rate * years / 100.

Program Practice

Python numbers and math FAQ

What is the difference between / and // in Python?

/ is true division and always returns a float (7 / 2 is 3.5). // is floor division and rounds down (7 // 2 is 3).

Why does 0.1 + 0.2 not equal 0.3 in Python?

Floats are stored in binary, which cannot represent 0.1 exactly. The result is 0.30000000000000004. Use math.isclose() or decimal.Decimal when exactness matters.

How do I round a number to 2 decimal places in Python?

Use round(x, 2) to get a number, or f"{x:.2f}" to get a string for display.

How do I get the square root in Python?

Use math.sqrt(x) after import math, or x ** 0.5.

Python User Input

Python Tutorial › Getting Started › User Input

Python User Input

BeginnerLesson 7 of 478 min read7 runnable examples

input() pauses your program and waits for the user to type something and press Enter. It is the simplest way to make a program interactive, and it is used in many practice programs.

In this lesson
  • Read text with input()
  • Convert input to numbers
  • Read several values from one line
  • Handle input that is not a number

Read text with input()

input() shows an optional prompt, waits for the user and returns what they typed as a string.

Python
name = input("What is your name? ")print("Hello,", name)
Outputtyped input: Asha
What is your name? Asha
Hello, Asha
Note

When you press Try it and Run on this site, your browser shows a small box for each input(). The recorded output above shows a run where the user typed Asha, exactly as it appears in a terminal.

input() always returns a string

Even if the user types digits, you get a string. Adding two strings joins them instead of adding numbers:

Python
a = input("First number: ")b = input("Second number: ")print(a + b)print(type(a))
Outputtyped input: 5, 7
First number: 5
Second number: 7
57
<class 'str'>

Convert input to a number

Wrap input() in int() for whole numbers or float() for decimals.

Python
qty = int(input("Quantity: "))price = float(input("Price: "))print("Total:", qty * price)
Outputtyped input: 5, 7.5
Quantity: 5
Price: 7.5
Total: 37.5
You wantUseExample inputResult
Textinput()pune'pune'
Whole numberint(input())4242
Decimal numberfloat(input())3.753.75

Several values on one line

split() breaks a string on spaces and returns a list. Combine it with map() to convert every part:

Python
numbers = input("Enter numbers separated by spaces: ").split()print(numbers) values = list(map(int, numbers))print(sum(values))
Outputtyped input: 10 20 30
Enter numbers separated by spaces: 10 20 30
['10', '20', '30']
60

Unpack directly into variables when you know how many values to expect:

Python
width, height = map(int, input("Width and height: ").split())print("Pixels:", width * height)
Outputtyped input: 1920 1080
Width and height: 1920 1080
Pixels: 2073600

Handle invalid input

If the user types abc, int() cannot convert it and raises a ValueError:

Python
age = int(input("Age: "))
Outputtyped input: abc
Age: abc
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    age = int(input("Age: "))
ValueError: invalid literal for int() with base 10: 'abc'

Catch the error with try / except and ask again. The Exception Handling lesson explains this pattern fully.

Python
while True:    text = input("Age: ")    try:        age = int(text)    except ValueError:        print(f"{text!r} is not a whole number, try again")        continue    if age < 0:        print("Age cannot be negative")        continue    break print("Age saved:", age)
Outputtyped input: abc, -3, 29
Age: abc
'abc' is not a whole number, try again
Age: -3
Age cannot be negative
Age: 29
Age saved: 29
Tip

text.strip() removes spaces the user typed by accident before or after the value. Use it before comparing input, for example input().strip().lower() == "yes".

Check your understanding

Quick quiz

1. The user types 8. What is the type of input()‘s result?

2. What does "3" + "4" give?

3. Which reads two whole numbers typed on one line as 4 9?

Exercise: rectangle calculator

Ask for the width and height on one line and print the area and the perimeter.

Input
4 6
Expected output
Width and height: 4 6
Area: 24
Perimeter: 20
Hint 1

split() then map(int, ...) gives you two numbers.

Hint 2

Perimeter is 2 * (width + height).

Program Practice

Many basic programs read their values with input(). Try changing a solution to ask the user instead of using fixed values.

Python input FAQ

How do I take integer input in Python?

Wrap input() in int(): n = int(input("Enter a number: ")). Use float() for decimal numbers.

How do I take multiple inputs in one line?

Use split(): a, b = input().split(). Add map(int, ...) to convert them to numbers.

What happens if the user enters text when I expect a number?

int() raises ValueError. Catch it with try / except ValueError and ask again.

Is raw_input() still available?

No. raw_input() was Python 2. In Python 3, input() does the same job and always returns a string.

Python Output & Comments

Python Tutorial › Getting Started › Output & Comments

Python Output & Comments

BeginnerLesson 6 of 4710 min read10 runnable examples

print() is how your program talks to you, and comments are how you talk to the next person who reads your code. Both look simple, but a few options make them far more useful.

In this lesson
  • Print several values at once
  • Control separators with sep and end
  • Print variables neatly with f-strings
  • Write comments and docstrings that help

The print() function

print() writes text to the screen and then moves to a new line. You can give it any value: text, numbers, lists or the result of a calculation.

Python
print("Hello, Python")print(42)print(3.5 * 2)print([1, 2, 3])print()                 # an empty lineprint("after the blank line")
Output
Hello, Python
42
7.0
[1, 2, 3]

after the blank line

Print several values

Separate values with commas. print() converts each one to text and puts a space between them, so you can mix text and numbers without converting anything.

Python
name = "Asha"tests = 12print("Tester:", name, "ran", tests, "tests")
Output
Tester: Asha ran 12 tests

Change the separator: sep

sep sets what goes between the values. The default is a single space.

Python
print("2026", "11", "02", sep="-")print("a", "b", "c", sep="")print("login", "search", "checkout", sep=" | ")
Output
2026-11-02
abc
login | search | checkout

Change the line ending: end

end sets what is printed after the last value. The default is a newline ("\n"), so each print() starts a new line. Change it to keep printing on the same line.

Python
for step in range(1, 4):    print("step", step, end=" -> ")print("finished")
Output
step 1 -> step 2 -> step 3 -> finished

Print variables with f-strings

An f-string starts with f before the quote. Anything in { } is replaced by its value. This is the clearest way to build output.

Python
item = "keyboard"price = 1499.5qty = 2print(f"{qty} x {item} = {price * qty}")print(f"Price with 2 decimals: {price:.2f}")print(f"{qty=}")
Output
2 x keyboard = 2999.0
Price with 2 decimals: 1499.50
qty=2
Tip

{qty=} prints both the name and the value, which is handy while debugging. The String Formatting lesson covers alignment, padding and number formats.

Escape characters

A backslash inside a string starts an escape sequence:

EscapePrints
\na new line
\ta tab
\\one backslash
\"a double quote inside a double-quoted string
Python
print("Name\tScore")print("Asha\t91")print("Line one\nLine two")print("She said \"hi\"")print("C:\\tests\\report.txt")
Output
Name	Score
Asha	91
Line one
Line two
She said "hi"
C:\tests\report.txt

Print to a file

print() can write to a file instead of the screen with the file argument. The File Handling lesson explains open() in detail.

Python
with open("log.txt", "w") as log:    print("test started", file=log)    print("test passed", file=log) print(open("log.txt").read())
Output
test started
test passed

Comments

A comment starts with #. Python ignores everything from # to the end of the line. Use comments to explain why the code does something, not what it obviously does.

Python
# Prices are stored in paise to avoid rounding errors with floatsprice_paise = 149950 discount = 0.10   # 10% festival discount, ends 15 Novfinal = price_paise * (1 - discount)print(final / 100)
Output
1349.55

Multi-line comments

Python has no special multi-line comment. Put # at the start of each line. Most editors do this for a selection with Ctrl+/.

Python
# Step 1: read the users file# Step 2: keep only active users# Step 3: print their namesusers = [("asha", True), ("ravi", False), ("meena", True)]print([name for name, active in users if active])
Output
['asha', 'meena']

Docstrings

A string written as the first line of a function, class or module is a docstring. Unlike a comment, Python keeps it, and help() shows it.

Python
def area(width, height):    """Return the area of a rectangle."""    return width * height print(area(3, 4))print(area.__doc__)
Output
12
Return the area of a rectangle.
Note

A triple-quoted string on its own in the middle of code is not a comment. Python creates the string and throws it away. It works, but # is the correct tool for comments.

Check your understanding

Predict the output

print("a", "b", sep="*", end="!")print("c")

Quick quiz

1. What is the default value of sep in print()?

2. Which line prints Total: 5 when n = 5?

3. How do you write a comment in Python?

Exercise: print a receipt line

Print one receipt line from these variables, with the price to 2 decimal places and | between the fields.

Input
item = "Mouse", qty = 3, price = 349.5
Expected output
Mouse | 3 | 1048.50
Hint 1

Use an f-string and the format :.2f for the total.

Program Practice

Python print and comments FAQ

How do I print without a newline in Python?

Pass end="" (or any other text) to print(), for example print("Loading", end="").

How do I print a variable with text?

Use an f-string, for example print(f"Total: {total}"), or pass several values: print("Total:", total).

How do I write a multi-line comment in Python?

Start each line with #. Triple-quoted strings are for docstrings, not comments.

What is the difference between a comment and a docstring?

Python ignores comments completely. A docstring is a real string stored on the function, class or module, and tools such as help() and IDEs display it.

Python Syntax

Python Tutorial › Getting Started › Python Syntax

Python Syntax

BeginnerLesson 5 of 479 min read9 runnable examples

Syntax is the set of rules for how Python code must be written. Python’s rules are few, but one of them, indentation, is stricter than in most languages. Learn these rules once and most beginner errors disappear.

In this lesson
  • How statements and lines work
  • Why indentation defines blocks
  • How to split long lines
  • Python keywords and case sensitivity

Statements and lines

A Python program is a list of statements, normally one per line. Python runs them from top to bottom. No semicolon is needed at the end of a line.

Python
city = "Pune"temperature = 31print(city, temperature)
Output
Pune 31

Indentation defines blocks

Many languages use curly braces { } to group lines. Python uses indentation: the spaces at the start of a line. A line ending in a colon : starts a block, and every line in that block must be indented by the same amount.

Python
score = 82 if score >= 50:    print("Passed")          # inside the if block    print("Well done")       # also insideprint("Report finished")     # outside: runs every time
Output
Passed
Well done
Report finished
Tip

Use 4 spaces per level. Every IDE inserts 4 spaces when you press Tab in a .py file. Never mix tabs and spaces in one file.

Wrong indentation is a syntax error, and Python refuses to run the file:

Python
if True:print("not indented")
Output
  File "main.py", line 2
    print("not indented")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 1

Indenting a line that should not be indented is also an error:

Python
print("one")    print("two")
Output
  File "main.py", line 2
    print("two")
IndentationError: unexpected indent

Blocks inside blocks

Each new block adds one more level of indentation. Python knows a block has ended when the indentation goes back.

Python
for n in [1, 2, 3, 4]:    if n % 2 == 0:        print(n, "is even")    else:        print(n, "is odd")print("done")
Output
1 is odd
2 is even
3 is odd
4 is even
done

Long lines

Python ends a statement at the end of the line, except inside brackets (), [] or {}. So the easiest way to split a long line is to wrap it in parentheses.

Python
total = (    120    + 80    + 45)names = ["login", "search",         "checkout"]print(total, names)
Output
245 ['login', 'search', 'checkout']

A backslash \ at the end of a line also continues it, but brackets are clearer and are what the PEP 8 style guide recommends.

Several statements on one line

A semicolon lets you put two statements on one line. It works, but it hurts readability, so use it rarely.

Python
a = 1; b = 2; print(a + b)
Output
3

Case sensitivity

Python is case-sensitive: name, Name and NAME are three different variables, and Print is not the same as print.

Python
name = "Asha"Name = "Ravi"print(name, Name)Print("hello")
Output
Asha Ravi
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    Print("hello")
    ^^^^^
NameError: name 'Print' is not defined. Did you mean: 'print'?

Keywords

Keywords are reserved words with a special meaning, such as if, for and def. You cannot use them as variable names. The keyword module lists them:

Python
import keywordprint(len(keyword.kwlist))print(keyword.kwlist)
Output
35
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Note

True, False and None are keywords too, and they start with a capital letter. true or none would be treated as ordinary (undefined) names.

Check your understanding

Predict the output

x = 5if x > 3:    print("big")print("end")if x > 10:    print("huge")

Quick quiz

1. What marks the start of a block in Python?

2. How many spaces per indentation level does PEP 8 recommend?

3. Which of these is a valid variable name?

Exercise: fix the indentation

This program should print “Even numbers:” once, then each even number, then “Done”. Fix the indentation so it runs.

Hint 1

Only the print(n) line belongs inside the if.

Hint 2

“Done” must print once, after the loop, so it should not be indented.

Program Practice

Python syntax FAQ

Does Python use semicolons?

Not normally. A newline ends a statement. A semicolon is only needed to put two statements on one line, which is rarely a good idea.

What is an IndentationError?

It is the error Python raises when lines in a block are not indented consistently, or when a block is missing after a colon.

Can I use tabs instead of spaces in Python?

Python accepts tabs, but not a mix of tabs and spaces in the same block. Use 4 spaces; every editor can insert them for you.

Is Python case-sensitive?

Yes. total and Total are different names, and built-in functions such as print must be lowercase.

Retries and Flaky Tests in Playwright Python with pytest-rerunfailures

A flaky test passes on one run and fails on the next, with no change in the code. Flaky tests destroy trust in a test suite: people stop believing red builds. The Playwright TypeScript runner has retries built in; in Python, the pytest-rerunfailures plugin provides them. In this lesson you will learn what makes Playwright tests flaky and how to fix the cause, then use retries correctly: –reruns, delays, the flaky marker, rerunning only specific errors, failing the build on flaky passes, artifacts per attempt, and finding flaky tests with pytest-repeat.

📖 What You’ll Learn: what a flaky test is and why it matters, common causes in browser tests and their fixes, installing pytest-rerunfailures, –reruns and the R progress letter, –reruns-delay, the flaky marker, –only-rerun and –rerun-except, why expect() timeouts are AssertionErrors, –fail-on-flaky, reruns in pytest.ini, screenshots and traces for each attempt, and repeating tests with pytest-repeat to expose flakiness.


🎲 What Is a Flaky Test?

A flaky test gives different results on different runs of the same code: green on your laptop, red in CI, green again when someone clicks “re-run”. It is one of the most expensive problems in test automation:

  • Real bugs hide among the “probably flaky again” failures.
  • Teams waste hours re-running pipelines and investigating ghosts.
  • People stop trusting the suite, and a suite nobody trusts is worth nothing.

A real example from this course: while Lesson 42 was being prepared, about one in six navigations to the public SauceDemo site stalled for more than 30 seconds, and the same unchanged tests failed with Page.goto: Timeout 30000ms exceeded in some runs and passed in others.


🔍 Common Causes and Their Real Fixes

Retries hide symptoms. Before you add them, look for the cause:

CauseSymptomReal fix
Checking too earlyPasses locally, fails on slow CIUse expect() assertions, never time.sleep() or one-shot reads like inner_text() (Module 5)
Shared state between testsFails only in a certain order or in parallelFresh context per test (the default), unique test data, no module-level globals
Animations and transitionsClicks land on a moving elementLet actionability checks work; disable animations for screenshots
Dependence on live third-party servicesRandom timeoutsMock the network (Module 8), or use a stable test environment
Dates, times and random dataFails around midnight or on certain valuesFix the time zone with timezone_id, control test data
Fragile locatorsFails after small UI changes or with A/B testsRole-based locators and test ids (Module 4)
Too-short timeoutsFails under loadTimeouts based on real requirements, not guesses

💡 Tip: The Trace Viewer (Module 5) is the best tool for flaky failures: run CI with --tracing retain-on-failure and compare the trace of a failed attempt with a passing one.


🔁 Retries with pytest-rerunfailures

Install the plugin:

⌨️ Terminal

pip install pytest-rerunfailures

This lesson uses version 16.7. To make the demonstrations repeatable, the test below simulates a flaky server. It shows a search result after a delay: 6 seconds on the first attempt (longer than expect()‘s 5-second timeout) and 1 second on later attempts. pytest-rerunfailures numbers the attempts in request.node.execution_count (1, 2, 3, …).

📄 flaky/test_flaky.py

from playwright.sync_api import Page, expect

RESULT_PAGE = """
<p id="result">Searching...</p>
<script>
  setTimeout(() => document.getElementById('result').textContent = '3 products found', {delay});
</script>
"""


def test_search_results(page: Page, request):
    attempt = getattr(request.node, "execution_count", 1)   # 1 = first try, 2 = first retry, ...
    delay = 6_000 if attempt == 1 else 1_000                # simulated slow server on the first try
    page.set_content(RESULT_PAGE.replace("{delay}", str(delay)))

    expect(page.locator("#result")).to_have_text("3 products found")
  • getattr(..., 1) returns 1 when the plugin is not active, so the test also runs without it.
  • In a real suite the delay comes from the server, not from your test. The simulation only makes the behaviour predictable for this lesson.

Without retries, the first attempt fails:

⌨️ Terminal

pytest -q flaky

🖥️ Output

F                                                                        [100%]
================================== FAILURES ===================================
________________________ test_search_results[chromium] ________________________

page = <Page url='about:blank'>
request = <FixtureRequest for <Function test_search_results[chromium]>>

    def test_search_results(page: Page, request):
        attempt = getattr(request.node, "execution_count", 1)   # 1 = first try, 2 = first retry, ...
        delay = 6_000 if attempt == 1 else 1_000                # simulated slow server on the first try
        page.set_content(RESULT_PAGE.replace("{delay}", str(delay)))
    
>       expect(page.locator("#result")).to_have_text("3 products found")
E       AssertionError: Locator expected to have text '3 products found'
E       Actual value: Searching... 
E       Call log:
E         - Expect "to_have_text" locator("#result") with timeout 5000ms
E         - waiting for locator("#result")
E           14 × locator resolved to <p id="result">Searching...</p>
E              - unexpected value "Searching..."
E       
E       Aria snapshot:
E       - paragraph: Searching...

flaky\test_flaky.py:16: AssertionError
=========================== short test summary info ===========================
FAILED flaky/test_flaky.py::test_search_results[chromium] - AssertionError: L...
1 failed, 1 warning in 5.56s

With retries, --reruns 2 allows up to two more attempts for a failed test:

⌨️ Terminal

pytest -q -rR flaky --reruns 2

🖥️ Output

R.                                                                       [100%]
=========================== rerun test summary info ===========================
RERUN flaky/test_flaky.py::test_search_results[chromium]
PASSED flaky/test_flaky.py::test_search_results[chromium]
1 passed, 1 warning, 1 rerun in 6.95s
  • R in the progress line means “failed, then rerun”; the final . is the passing attempt.
  • The summary counts reruns separately: 1 passed, 1 rerun. The run’s exit code is 0.
  • -rR adds the “rerun test summary info” section that lists which tests needed a rerun. Keep an eye on this list: every entry is a flaky test to investigate.
  • Each attempt runs the test’s fixtures again: a new context and a new page.

⚙️ Retry Options

OptionMeaning
--reruns NRerun a failed test up to N times
--reruns-delay SWait S seconds before each rerun (for example, to let a service recover)
--only-rerun REGEXRerun only failures whose error matches the regex; repeatable
--rerun-except REGEXDo not rerun failures that match the regex; repeatable
--fail-on-flakyFail the run with exit code 7 if any test passed only after a rerun
--max-suite-reruns NLimit the total number of reruns in the whole run
--force-reruns NUse N reruns for every test, ignoring markers

The same settings work in pytest.ini:

[pytest]
addopts = --reruns 2 --reruns-delay 1

pytest-rerunfailures 16.7 also has its own ini keys, such as reruns = 2, reruns_delay = 1, only_rerun and rerun_except.

Retry only infrastructure errors: –only-rerun

A retry makes sense for problems outside your application, such as a slow network. It makes no sense for a wrong text, which will be wrong again on the next attempt. Here is a real bug and a slow page in one file:

📄 filters/test_filters.py

from playwright.sync_api import Page, expect

SLOW_BUTTON = """
<script>
  setTimeout(() => document.body.innerHTML = '<button>Checkout</button>', {delay});
</script>
"""


def test_wrong_heading(page: Page):
    page.set_content("<h1>Cart</h1>")
    expect(page.locator("h1")).to_have_text("Basket", timeout=1_000)   # a real bug: wrong text


def test_slow_button(page: Page, request):
    attempt = getattr(request.node, "execution_count", 1)
    page.set_content(SLOW_BUTTON.replace("{delay}", "3000" if attempt == 1 else "200"))
    page.get_by_role("button", name="Checkout").click(timeout=2_000)       # an action timeout

⌨️ Terminal

pytest -q filters --reruns 2 --only-rerun TimeoutError

🖥️ Output

FR.                                                                      [100%]
================================== FAILURES ===================================
________________________ test_wrong_heading[chromium] _________________________

page = <Page url='about:blank'>

    def test_wrong_heading(page: Page):
        page.set_content("<h1>Cart</h1>")
>       expect(page.locator("h1")).to_have_text("Basket", timeout=1_000)   # a real bug: wrong text
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       AssertionError: Locator expected to have text 'Basket'
E       Actual value: Cart 
E       Call log:
E         - Expect "to_have_text" locator("h1") with timeout 1000ms
E         - waiting for locator("h1")
E           11 × locator resolved to <h1>Cart</h1>
E              - unexpected value "Cart"
E       
E       Aria snapshot:
E       - heading "Cart" [level=1]

filters\test_filters.py:12: AssertionError
=========================== short test summary info ===========================
FAILED filters/test_filters.py::test_wrong_heading[chromium] - AssertionError...
1 failed, 1 passed, 1 warning, 1 rerun in 4.07s
  • test_slow_button failed with Playwright’s TimeoutError on the first attempt, matched TimeoutError, was rerun and passed.
  • test_wrong_heading failed without a rerun. A failed expect() raises an AssertionError, even when it waited for its timeout, so it does not match TimeoutError.

📝 Note: This difference is useful. Action and navigation timeouts (click, fill, goto) raise TimeoutError, often caused by the environment. Failed expect() checks raise AssertionError, more often a real difference in the application. --only-rerun TimeoutError therefore retries infrastructure problems while real assertion failures fail at once.

Failing the build on flaky passes: –fail-on-flaky

Some teams want retries to keep the pipeline moving, but still want to know about flakiness. --fail-on-flaky lets the tests pass on retry but ends the run with exit code 7:

⌨️ Terminal

pytest -q flaky --reruns 2 --fail-on-flaky

🖥️ Output

R.                                                                       [100%]
1 passed, 1 warning, 1 rerun in 6.96s

The summary still says 1 passed, 1 rerun, but pytest exited with code 7 (in our run, the verification script recorded exit 7), so CI marks the job as failed and someone has to look at the flaky test.


🏷️ The flaky Marker: Retries for Specific Tests

Instead of retrying the whole suite, mark only the tests you know are affected:

📄 marker/test_marker.py

import pytest
from playwright.sync_api import Page, expect

RESULT_PAGE = """
<p id="result">Searching...</p>
<script>
  setTimeout(() => document.getElementById('result').textContent = 'done', {delay});
</script>
"""


@pytest.mark.flaky(reruns=3, reruns_delay=1, only_rerun=["AssertionError"])
def test_known_slow_search(page: Page, request):
    attempt = request.node.execution_count
    print(f"\nattempt {attempt}")
    page.set_content(RESULT_PAGE.replace("{delay}", "4000" if attempt < 3 else "100"))
    expect(page.locator("#result")).to_have_text("done", timeout=2_000)

⌨️ Terminal

pytest -q -s marker

🖥️ Output

attempt 1
R
attempt 2
R
attempt 3
.
1 passed, 1 warning, 2 rerun in 6.89s
  • reruns=3 allows three reruns for this test only, without any command-line option.
  • reruns_delay=1 waits one second between attempts.
  • only_rerun= (and rerun_except=) work in the marker too. Here the test’s failures are AssertionErrors from expect(), so they are listed explicitly.
  • The test failed twice (each R) and passed on attempt 3; the summary counts 2 rerun.
  • When both the marker and --reruns are given, the marker wins by default (--reruns-mode strict).

⚠️ Watch out: A flaky marker is a temporary measure. Add a comment with the reason and a ticket number, and remove the marker once the cause is fixed. A suite where many tests carry it has a flakiness problem that retries only hide.


📸 Artifacts for Each Attempt

When you combine retries with pytest-playwright’s artifacts, each failed attempt keeps its own evidence. Run the simulated flaky test with one rerun and screenshots on failure:

⌨️ Terminal

pytest -q flaky --reruns 1 --screenshot only-on-failure

🖥️ Output

R.                                                                       [100%]
1 passed, 1 warning, 1 rerun in 7.00s

The output folder now contains:

🖥️ Output

test-results/flaky-test-flaky-py-test-search-results-chromium/test-failed-1.png
  • The screenshot of the first, failed attempt is kept, which is exactly the evidence you need to understand the flaky failure.
  • The retry passed, so it kept nothing. A failed retry would have its own folder ending in -retry1, as you saw in Module 5.
  • With --tracing retain-on-failure, you get a trace of the failed attempt too: the best way to see why it was slow.

🔂 Finding Flaky Tests: pytest-repeat

To check whether a test is stable before it causes trouble in CI, run it many times. The pytest-repeat plugin (version 0.9.4 here) adds --count:

⌨️ Terminal

pip install pytest-repeat

📄 repeat/test_repeat.py

from playwright.sync_api import Page, expect


def test_practice_page_title(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page).to_have_title("Automation Practice Page - SQA Tools")

⌨️ Terminal

pytest repeat --count 3 -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\pwv\_venv\Scripts\python.exe
...
plugins: html-4.2.0, metadata-3.1.1, playwright-0.10.0, repeat-0.9.4, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 3 items

repeat/test_repeat.py::test_practice_page_title[chromium-1-3] PASSED     [ 33%]
repeat/test_repeat.py::test_practice_page_title[chromium-2-3] PASSED     [ 66%]
repeat/test_repeat.py::test_practice_page_title[chromium-3-3] PASSED     [100%]

======================== 3 passed, 1 warning in 6.59s =========================
  • Each repetition gets its own test id (1-3, 2-3, 3-3) and a fresh context.
  • For a real stability check, use a higher count, such as --count 50, and add -x to stop at the first failure. Combine it with pytest-xdist (Module 12) to finish faster.
  • Do not combine --count with --reruns for this purpose: retries would hide exactly the failures you are looking for.

✅ A Sensible Retry Policy

  1. Locally: no retries. You want to see every failure while you work.
  2. In CI: a small number, such as --reruns 1 or --reruns 2, ideally with --only-rerun TimeoutError for infrastructure problems.
  3. Always keep evidence: --tracing retain-on-failure and --screenshot only-on-failure.
  4. Track every rerun. Use -rR or the report to list flaky tests, and fix them like bugs; consider --fail-on-flaky once the suite is mostly stable.
  5. Never use retries to hide a real failure. A test that fails 1 time in 10 because of the application is a bug report, not noise.

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Write the command that reruns failed tests up to twice with a 2-second delay, but only for Playwright TimeoutError failures.

Show answer
pytest --reruns 2 --reruns-delay 2 --only-rerun TimeoutError

Exercise 2: Mark one known-flaky test with three reruns using the marker, and explain why fixing the cause is still the goal.

Show answer
@pytest.mark.flaky(reruns=3, reruns_delay=1)
def test_slow_third_party_widget(page): ...

Reruns only hide the symptom: the test can still fail, wastes time, and may hide a real intermittent bug. Find the cause (timing, shared data, unstable dependency) with traces and fix it, then remove the marker.

Exercise 3: How do you find out whether a test is flaky before it bothers the team? Write the command.

Show answer
pip install pytest-repeat
pytest tests/test_checkout.py --count 20 -x

Repeating a test many times (optionally in parallel with -n) exposes intermittent failures early.


🧠 MCQ Quiz: Retries and Flaky Tests (pytest-rerunfailures)

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What is a flaky test?
  2. Which plugin adds --reruns?
  3. What does the letter R mean in pytest’s progress line?
  4. What exception does a failed expect() raise?
  5. What does --fail-on-flaky do?
  6. Which is the best first fix for a test that fails because it checks too early?
  7. Do function-scoped fixtures run again on a rerun?
  8. Which plugin repeats a test N times to expose flakiness?
  9. What is a common cause of flakiness in parallel runs?
  10. What should a team track about retries?

Want a longer, timed test? Take the Module 6 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Does Playwright Python have built-in retries like playwright.config.ts?

No. The TypeScript test runner has a retries setting. In Python, retries come from the pytest-rerunfailures plugin: --reruns N or the flaky marker.

🤔 Are fixtures run again on a rerun?

Yes. Each attempt is a complete run of the test, with its function-scoped fixtures (including page and context) set up and torn down again. Session-scoped fixtures, such as the browser, are reused.

🤔 Why is my expect() failure not retried with –only-rerun TimeoutError?

A failed expect() raises AssertionError, not TimeoutError. Only actions and navigations (click, fill, goto) raise Playwright’s TimeoutError. Use --only-rerun AssertionError if you really want to retry assertion failures.

🤔 How do I know which tests are flaky?

Look for R in the progress line and use -rR to list rerun tests in the summary. Run suspicious tests many times with pytest-repeat’s --count.

🤔 Can I use –reruns together with pytest-xdist?

Yes. Each worker reruns its own failed tests. Parallel runs are covered in Module 12.


🏁 Summary

  • Flaky tests pass and fail on the same code; fix their causes first: waits, shared state, live dependencies, data and locators.
  • pytest-rerunfailures adds retries: --reruns N, --reruns-delay, the flaky marker, and filters with --only-rerun and --rerun-except.
  • Failed expect() checks raise AssertionError; action and navigation timeouts raise TimeoutError.
  • --fail-on-flaky exits with code 7 when a test only passed on retry; -rR lists rerun tests.
  • Failed attempts keep their screenshots and traces; pytest-repeat’s --count exposes flakiness before CI does.

You have finished Module 6. Test yourself with the Module 6 mock interview, then continue to Module 7: test data, configuration and cross-browser testing at scale.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Browser Markers in pytest-playwright: skip_browser, only_browser and browser_context_args

One of Playwright’s biggest strengths is real cross-browser testing: the same test runs on Chromium, Firefox and WebKit. Sometimes, though, a test should not run everywhere: a feature is missing in one engine, or the test uses a Chromium-only API. pytest-playwright gives you markers for exactly that. In this lesson you will run a suite on all three engines, find a real browser difference on the practice page, and control where each test runs with skip_browser, only_browser, browser_context_args, browser channels and per-test launch options.

📖 What You’ll Learn: running tests on several browsers with –browser, reading the parametrized test ids, a real WebKit difference on the practice page, skip_browser and only_browser, showing skip reasons with -rs, markers on classes and modules, branching on browser_name, the browser_context_args marker for per-test context options, browser channels for Google Chrome and Microsoft Edge, and per-test launch options with indirect parametrization of browser_type_launch_args.


🌍 Running on Several Browsers

By default pytest-playwright runs every test on Chromium. Pass --browser once per engine to run on more:

⌨️ Terminal

pytest --browser chromium --browser firefox --browser webkit

Each --browser creates one copy of every browser test, with the engine in the test id: test_title[chromium], test_title[firefox], test_title[webkit]. Each engine gets its own browser process; every test still gets a fresh context.

EngineUsed byNotes
ChromiumGoogle Chrome, Microsoft Edge, OperaPlaywright’s default
FirefoxMozilla FirefoxPlaywright’s patched build
WebKitApple SafariPlaywright’s WebKit build runs on Windows, Linux and macOS

📝 Note: Playwright’s WebKit is close to Safari but not identical: the real Safari also depends on the Apple operating system it runs on. It is still the best way to catch WebKit-specific problems without a Mac.


🔎 A Real Difference Between Engines

All tests in this lesson use the SQA Tools practice page:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page

The page has a date picker, <input type="date" id="datePicker">. This test asks each browser what kind of input it actually created:

📄 tests/test_cross_browser.py

import pytest
from playwright.sync_api import Page, expect


def test_title(practice: Page, browser_name):
    print(f"\n{browser_name} {practice.context.browser.version}")
    expect(practice).to_have_title("Automation Practice Page - SQA Tools")


def test_what_is_the_date_input(practice: Page, browser_name):
    input_type = practice.locator("#datePicker").evaluate("el => el.type")
    print(f"\n{browser_name}: #datePicker has type '{input_type}'")
  • practice.context.browser.version is the version of the browser that runs the test.
  • el.type returns the type the browser supports: a browser without a date control falls back to a plain text box and reports "text".

When this lesson was run on Windows, Chromium and Firefox reported date, but **WebKit reported text**: Playwright’s WebKit build on Windows has no native date picker (you will see this in the output below). A test that fills the date picker in the YYYY-MM-DD format and expects a date control would fail there for a reason that has nothing to do with your application.


⏭️ skip_browser and only_browser

pytest-playwright registers two markers for such cases:

📄 tests/test_cross_browser.py

@pytest.mark.skip_browser("webkit")
def test_date_picker(practice: Page):
    practice.locator("#datePicker").fill("2026-11-01")
    expect(practice.locator("#datePicker")).to_have_value("2026-11-01")


@pytest.mark.only_browser("chromium")
def test_chromium_devtools_protocol(practice: Page):
    # CDP sessions exist only in Chromium-based browsers
    cdp = practice.context.new_cdp_session(practice)
    version = cdp.send("Browser.getVersion")
    print("\nCDP product:", version["product"].split("/")[0])
  • @pytest.mark.skip_browser("webkit"): run on every browser except WebKit.
  • @pytest.mark.only_browser("chromium"): run only on Chromium; all other browsers are skipped.
  • new_cdp_session() talks to the Chrome DevTools Protocol, which only Chromium-based browsers support. That makes it a genuine reason for only_browser.
  • Skipped copies appear as s in the progress line. Add -rs to the pytest command to list each skip with its reason.

⚠️ Watch out: Use these markers for real engine limitations, not to hide bugs. If your application is broken in Safari, a skipped test means your users find the bug instead of you. Mark such tests with xfail and a ticket number, or fix the application.

Markers on a whole class or module

Markers can be applied to a class, and to a whole file with pytestmark:

📄 tests/test_firefox_suite.py

import pytest
from playwright.sync_api import Page, expect


@pytest.mark.only_browser("firefox")
class TestFirefoxSpecific:
    def test_user_agent(self, practice: Page):
        expect(practice.locator("body")).to_be_visible()
        assert "Firefox" in practice.evaluate("navigator.userAgent")

    def test_engine_name(self, practice: Page, browser_name):
        assert browser_name == "firefox"

For a whole module, write pytestmark = pytest.mark.skip_browser("webkit") at the top of the file.

Branching inside a test with browser_name

When only one step differs, skip that part or adapt the expected value instead of skipping the whole test:

📄 tests/test_cross_browser.py

ENGINE_IN_USER_AGENT = {"chromium": "Chrome", "firefox": "Firefox", "webkit": "AppleWebKit"}


def test_user_agent_matches_engine(practice: Page, browser_name):
    user_agent = practice.evaluate("navigator.userAgent")
    assert ENGINE_IN_USER_AGENT[browser_name] in user_agent
  • A dictionary keyed by browser_name keeps browser-specific expectations in one readable place.
  • You can also call pytest.skip("reason") inside the test after checking browser_name or is_webkit. Prefer the markers when the whole test does not apply: the decision is then visible without reading the test body.

🎛️ The browser_context_args Marker

You met this marker in Lesson 6. It adds or overrides context options for one test (or one class), on top of the browser_context_args fixture:

📄 tests/test_context_marker.py

import pytest
from playwright.sync_api import Page


@pytest.mark.browser_context_args(locale="de-DE", timezone_id="Europe/Berlin")
def test_german_user(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    language = page.evaluate("navigator.language")
    zone = page.evaluate("Intl.DateTimeFormat().resolvedOptions().timeZone")
    print(f"\nlanguage={language} timezone={zone}")
    assert (language, zone) == ("de-DE", "Europe/Berlin")
  • The marker’s keyword arguments are passed to browser.new_context() for this test’s context.
  • Typical uses: a different locale or time zone, color_scheme="dark", permissions=["geolocation"], a mobile viewport, or storage_state for a test that should start logged in.

Now run the whole tests folder on all three engines, with -rs to show skip reasons:

⌨️ Terminal

pytest -q -s -rs tests --browser chromium --browser firefox --browser webkit

🖥️ Output

language=de-DE timezone=Europe/Berlin
.
chromium 156.0.8078.4
.
chromium: #datePicker has type 'date'
..
CDP product: HeadlessChrome
..ss
language=de-DE timezone=Europe/Berlin
.
firefox 157.0
.
firefox: #datePicker has type 'date'
..s...
language=de-DE timezone=Europe/Berlin
.
webkit 27.2
.
webkit: #datePicker has type 'text'
.ss.ss
=========================== short test summary info ===========================
SKIPPED [2] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: chromium
SKIPPED [1] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: firefox
SKIPPED [4] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: webkit
17 passed, 7 skipped, 1 warning in 38.09s

Read the result:

  • The #datePicker lines show the real engine difference: date in Chromium and Firefox, text in WebKit.
  • test_date_picker[webkit] was skipped by skip_browser; the CDP test and the Firefox class were skipped on the other engines by only_browser. The reason for each skip is listed in the short test summary, because of -rs.
  • pytest groups the run by browser: all Chromium tests first, then Firefox, then WebKit, because each engine’s browser is a separate session fixture.
  • The skips add up: Chromium skipped the two Firefox-only tests, Firefox skipped the CDP test, and WebKit skipped the date picker, the CDP test and the two Firefox-only tests.
  • The reason text is fixed by the plugin (“skipped for this browser: …”) and points at the plugin’s code line, not at your test.

🏷️ Browser Channels: Google Chrome and Microsoft Edge

Playwright’s Chromium is an open-source build. To test with the branded browsers installed on the machine, pass a channel:

⌨️ Terminal

pytest -q -s tests/test_cross_browser.py::test_title --browser-channel msedge

🖥️ Output

chromium 156.0.4314.42
.
1 passed, 1 warning in 2.70s
  • --browser-channel msedge launched the Microsoft Edge installed on this Windows machine, so the version is Edge’s own version number. chrome selects Google Chrome; beta and dev channels exist too (chrome-beta, msedge-beta, …).
  • The test id still says [chromium], because a channel is a Chromium-based browser.
  • A channel uses the browser installed on the machine. Install it there first (for Chrome you can also run playwright install chrome).

🚀 Per-Test Launch Options

Context options change the page environment (locale, viewport, permissions). Launch options change the browser process itself: command-line arguments, slow_mo, headless, channel. The suite-wide way to set them is overriding the browser_type_launch_args fixture (Lesson 6). For a single test, parametrize that fixture indirectly:

📄 launch/test_launch_args.py

import pytest
from playwright.sync_api import Page


@pytest.mark.only_browser("chromium")
@pytest.mark.parametrize(
    "browser_type_launch_args",
    [{"args": ["--lang=de-DE"]}],
    indirect=True,
)
def test_browser_started_in_german(page: Page, browser_type_launch_args):
    print("\nlaunch args:", browser_type_launch_args)
    print("navigator.language:", page.evaluate("navigator.language"))
  • indirect=True sends the value to the browser_type_launch_args fixture instead of passing it straight to the test. In pytest-playwright 0.10, the fixture merges it over the command-line launch options.
  • --lang=de-DE is a Chromium command-line switch, so the test is limited to Chromium with only_browser.
  • Because browser_type_launch_args and browser are session-scoped, each distinct value launches its own browser. That is slower, so keep per-test launch options for the few tests that really need them.

⌨️ Terminal

pytest -q -s -rs launch --browser chromium --browser firefox

🖥️ Output

launch args: {'args': ['--lang=de-DE']}
navigator.language: de
.s
=========================== short test summary info ===========================
SKIPPED [1] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: firefox
1 passed, 1 skipped, 1 warning in 0.57s
  • The browser started with --lang=de-DE, so navigator.language is de, without any context option.
  • On Firefox the test was skipped by the only_browser marker.
  • The test id is test_browser_started_in_german[chromium-browser_type_launch_args0]: the parameter gets an automatic id. Pass ids=["german"] to parametrize for a readable one.

📋 Which Tool for Which Need?

NeedUse
Run the suite on several engines--browser chromium --browser firefox --browser webkit
A test that cannot work on one engine@pytest.mark.skip_browser("webkit")
A test that uses an engine-specific API@pytest.mark.only_browser("chromium")
One step that differs per enginebrowser_name, is_webkit and friends inside the test
Locale, time zone, viewport, permissions for one test@pytest.mark.browser_context_args(...)
The same for every testOverride the browser_context_args fixture
Branded Chrome or Edge--browser-channel chrome or msedge
Browser command-line switches for one testIndirect parametrization of browser_type_launch_args

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Mark a test so it never runs in WebKit, and another so it runs only in Chromium. Then show the command that runs all browsers and prints the skip reasons.

Show answer
@pytest.mark.skip_browser("webkit")
def test_not_on_webkit(page): ...


@pytest.mark.only_browser("chromium")
def test_cdp_feature(page): ...
pytest --browser chromium --browser firefox --browser webkit -rs

Exercise 2: Give one test a German locale and a 400×800 viewport without affecting other tests.

Show answer
@pytest.mark.browser_context_args(locale="de-DE", viewport={"width": 400, "height": 800})
def test_german_mobile(page):
    assert page.evaluate("navigator.language") == "de-DE"

Exercise 3: Mark every test in a module to skip Firefox.

Show answer
import pytest

pytestmark = pytest.mark.skip_browser("firefox")

🧠 MCQ Quiz: Browser Markers and browser_context_args

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does @pytest.mark.skip_browser("webkit") do?
  2. What does @pytest.mark.only_browser("chromium") do?
  3. How do you see why tests were skipped?
  4. Which marker changes context options for one test?
  5. How do you apply a browser marker to a whole class?
  6. When is branching on browser_name inside a test acceptable?
  7. How do you run tests in Microsoft Edge?
  8. How many results does one test produce with --browser chromium --browser firefox?
  9. Which module-level variable applies markers to all tests in a file?
  10. Why always give a reason when skipping a browser?

Want a longer, timed test? Take the Module 6 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 How do I run Playwright Python tests on all browsers?

Pass --browser once per engine: pytest --browser chromium --browser firefox --browser webkit. Put it in addopts in pytest.ini to make it the default.

🤔 What is the difference between skip_browser and only_browser?

skip_browser("webkit") excludes one engine and runs on the rest. only_browser("chromium") runs on one engine and skips all others.

🤔 Why is my only_browser test always skipped?

It only runs when that browser is part of the run. With only_browser("firefox") and no --browser firefox, every copy of the test is skipped.

🤔 Is WebKit on Windows the same as Safari?

No. It is Playwright’s build of the WebKit engine, so it behaves like Safari in most respects but not all, as the date input in this lesson shows. Run important Safari checks on macOS as well.

🤔 Can I set a different viewport for one test?

Yes: @pytest.mark.browser_context_args(viewport={"width": 390, "height": 844}), or create a context with new_context(viewport=...) inside the test.


🏁 Summary

  • --browser runs every browser test once per engine; the engine appears in the test id.
  • Engines differ: on Windows, WebKit has no native date input on the practice page.
  • skip_browser and only_browser decide where a test runs; -rs shows why tests were skipped.
  • Apply markers to classes or whole modules (pytestmark), and branch on browser_name for small differences.
  • The browser_context_args marker changes context options for one test; --browser-channel runs branded Chrome or Edge.
  • Indirect parametrization of browser_type_launch_args sets launch options for one test, at the cost of a separate browser launch.

Next, you will deal with tests that fail only sometimes: why tests become flaky, and how to retry them with pytest-rerunfailures without hiding real problems.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Custom Fixtures for Playwright Python Tests (Page Objects, Login, Factories)

The built-in page fixture gives every test an empty browser tab. Real tests need more: an opened login page, a user who is already logged in, products in the cart, a check that no JavaScript errors happened. Custom fixtures turn that preparation into one reusable word in the test’s parameter list. In this lesson you will build a small fixture library for the SauceDemo shop on top of pytest-playwright’s fixtures, including a session-scoped login that is reused by every test.

📖 What You’ll Learn: why custom fixtures keep Playwright tests short, a page object fixture, chaining fixtures into a logged-in page, logging in once per session with storage_state and new_context, factory fixtures that take arguments, yield teardown, a fixture that collects console and page errors, parametrized fixtures for desktop and mobile, the ScopeMismatch error and the scope rules for fixtures that use page.


🧩 Why Custom Fixtures?

Compare two versions of the same test. Without fixtures, every test repeats the setup:

def test_cart_badge(page):
    page.goto("https://www.saucedemo.com/")
    page.get_by_placeholder("Username").fill("standard_user")
    page.get_by_placeholder("Password").fill("secret_sauce")
    page.get_by_role("button", name="Login").click()
    # ... and only now the actual test starts

With fixtures, the test says only what it is about:

def test_cart_badge(add_to_cart):
    page = add_to_cart("Sauce Labs Backpack")
    expect(page.locator(".shopping_cart_badge")).to_have_text("1")

You already know how fixtures work (Module 3). This lesson is about Playwright-specific fixtures: building on page, new_context and browser, choosing the right scope, and keeping tests isolated.

All examples use SauceDemo (www.saucedemo.com), a public practice shop. Its login page lists the demo user names and the shared password secret_sauce.

📝 Note: SauceDemo is a shared public site. While this lesson was being prepared, roughly one navigation in six stalled for more than 30 seconds, and the tests then failed with Page.goto: Timeout 30000ms exceeded. If that happens to you, simply run the tests again. Lesson 44 shows how to handle such flaky failures with automatic retries.


🏗️ The Fixture Library: conftest.py

Here is the start of conftest.py. The rest of the file follows in the next sections.

📄 conftest.py

import pytest
from playwright.sync_api import Browser, Page, expect

SAUCE = "https://www.saucedemo.com/"
USER = {"username": "standard_user", "password": "secret_sauce"}   # public demo account


class LoginPage:
    """A tiny page object for the SauceDemo login page."""

    def __init__(self, page: Page):
        self.page = page
        self.username = page.get_by_placeholder("Username")
        self.password = page.get_by_placeholder("Password")
        self.button = page.get_by_role("button", name="Login")
        self.error = page.locator("[data-test='error']")

    def open(self) -> "LoginPage":
        self.page.goto(SAUCE, wait_until="domcontentloaded")
        return self

    def login(self, username: str, password: str) -> None:
        self.username.fill(username)
        self.password.fill(password)
        self.button.click()


# 1. A page object fixture: the login page, already opened
@pytest.fixture
def login_page(page: Page) -> LoginPage:
    return LoginPage(page).open()


# 2. Chained fixture: a page where the user is logged in
@pytest.fixture
def logged_in_page(login_page: LoginPage) -> Page:
    login_page.login(**USER)
    expect(login_page.page).to_have_url(f"{SAUCE}inventory.html")
    return login_page.page

1. A page object fixture

  • LoginPage groups the login page’s locators and actions in one class. This is the Page Object Model, covered in depth in Module 10.
  • The login_page fixture builds on pytest-playwright’s page, opens the page and returns the object. A test that asks for login_page starts on the login screen.
  • wait_until="domcontentloaded": as you saw in Module 5, a public site’s load event can be slow because of third-party resources. The locators wait for the form anyway.

2. Chaining fixtures into a logged-in page

  • logged_in_page asks for login_page, which asks for page. pytest resolves the chain: page → login_page → logged_in_page.
  • The fixture ends with an expect(): if the login fails, the fixture fails with a clear message, and pytest reports the test as an error in setup rather than a failure in the test body. That tells you immediately that the problem is in the preparation.

📄 tests/test_login.py

from playwright.sync_api import Page, expect


def test_locked_out_user_sees_error(login_page):
    login_page.login("locked_out_user", "secret_sauce")
    expect(login_page.error).to_have_text("Epic sadface: Sorry, this user has been locked out.")


def test_products_are_listed(logged_in_page: Page):
    expect(logged_in_page.locator(".title")).to_have_text("Products")
    expect(logged_in_page.locator(".inventory_item")).to_have_count(6)

🔐 Logging In Once: a Session Fixture with storage_state

Logging in through the form in every test costs time. A faster pattern: log in once per session, save the browser’s cookies and storage to a file, and start every test’s context from that file.

📄 conftest.py

# 3. Log in once for the whole session and save the browser state
@pytest.fixture(scope="session")
def auth_state(browser: Browser, tmp_path_factory) -> str:
    context = browser.new_context()
    page = context.new_page()
    LoginPage(page).open().login(**USER)
    page.wait_for_url("**/inventory.html")

    path = tmp_path_factory.mktemp("auth") / "state.json"
    context.storage_state(path=path)       # cookies + localStorage as JSON
    context.close()
    print(f"\n[auth_state] logged in once, saved {path.name}")
    return str(path)


# 4. Each test gets a NEW context that starts from the saved state
@pytest.fixture
def fast_logged_in_page(new_context, auth_state: str) -> Page:
    page = new_context(storage_state=auth_state).new_page()
    page.goto(f"{SAUCE}inventory.html", wait_until="domcontentloaded")
    return page
  • auth_state is session-scoped, so it may only use session-scoped fixtures. It uses browser (session) and pytest’s built-in tmp_path_factory (session), not page (function).
  • context.storage_state(path=...) writes the context’s cookies and localStorage to a JSON file. SauceDemo keeps the login in a cookie named session-username.
  • fast_logged_in_page calls new_context(storage_state=...): a fresh, isolated context per test, which already contains the login cookie. The test lands directly on the products page.

📄 tests/test_fast_login.py

from playwright.sync_api import Page, expect


def test_first_fast_login(fast_logged_in_page: Page):
    expect(fast_logged_in_page.locator(".title")).to_have_text("Products")


def test_second_fast_login(fast_logged_in_page: Page):
    expect(fast_logged_in_page).to_have_url("https://www.saucedemo.com/inventory.html")

Run them with --setup-show to see that the login happens only once (an excerpt; ... marks lines removed for brevity):

⌨️ Terminal

pytest -q --setup-show tests/test_fast_login.py

🖥️ Output

...
SETUP    S browser (fixtures used: launch_browser)
...
SETUP    S tmp_path_factory
SETUP    S auth_state (fixtures used: browser, tmp_path_factory)
        ...
        SETUP    F new_context (fixtures used: _artifacts_recorder, browser, browser_context_args)
        SETUP    F fast_logged_in_page (fixtures used: auth_state, new_context)
        tests/test_fast_login.py::test_first_fast_login[chromium] (fixtures used: ...) .
        TEARDOWN F fast_logged_in_page
        TEARDOWN F new_context
        ...
        SETUP    F new_context (fixtures used: _artifacts_recorder, browser, browser_context_args)
        SETUP    F fast_logged_in_page (fixtures used: auth_state, new_context)
        tests/test_fast_login.py::test_second_fast_login[chromium] (fixtures used: ...) .
        TEARDOWN F fast_logged_in_page
        TEARDOWN F new_context
        ...
TEARDOWN S auth_state
TEARDOWN S tmp_path_factory
...
2 passed, 1 warning in 8.65s

SETUP S auth_state appears once, before the first test; both tests then create their own F fast_logged_in_page. Module 8 builds on this pattern for real authentication setups.

⚠️ Watch out: Never commit real credentials in conftest.py. The SauceDemo values are public demo data. For your own applications, read user names and passwords from environment variables or a secrets store (Module 7).


🏭 Factory Fixtures: Fixtures That Take Arguments

A fixture cannot receive arguments from the test directly. The solution is a factory: the fixture returns a function, and the test calls it with the arguments it needs.

📄 conftest.py

# 5. A factory fixture: the test decides which products to add
@pytest.fixture
def add_to_cart(logged_in_page: Page):
    added = []

    def _add(product: str) -> Page:
        item = logged_in_page.locator(".inventory_item").filter(has_text=product)
        item.get_by_role("button", name="Add to cart").click()
        added.append(product)
        return logged_in_page

    yield _add

    # Teardown: runs after the test, even if it failed
    print(f"\n[add_to_cart] teardown, products added in this test: {added}")

📄 tests/test_cart.py

from playwright.sync_api import expect


def test_one_product(add_to_cart):
    page = add_to_cart("Sauce Labs Backpack")
    expect(page.locator(".shopping_cart_badge")).to_have_text("1")


def test_two_products(add_to_cart):
    add_to_cart("Sauce Labs Backpack")
    page = add_to_cart("Sauce Labs Bike Light")
    expect(page.locator(".shopping_cart_badge")).to_have_text("2")
  • yield _add hands the inner function to the test. Everything after yield is teardown.
  • The added list remembers what the test did, so teardown knows what to clean up.
  • Here teardown only prints, because the browser context, and with it SauceDemo’s cart, is thrown away after each test anyway. In a real application the cart or order may live in a database: that is where teardown matters, for example to delete the order through an API call.

🚨 A Fixture That Watches the Page: Console and Page Errors

Fixtures can also attach listeners to the page. This one collects JavaScript errors so a test can assert that none happened:

📄 conftest.py

# 6. Collect console errors and uncaught exceptions of the page
@pytest.fixture
def js_errors(page: Page) -> list[str]:
    errors: list[str] = []
    page.on("console", lambda msg: errors.append(f"console: {msg.text}") if msg.type == "error" else None)
    page.on("pageerror", lambda exc: errors.append(f"pageerror: {exc}"))
    return errors

📄 tests/test_js_errors.py

from playwright.sync_api import Page, expect


def test_page_with_a_broken_script(page: Page, js_errors):
    page.set_content("""
        <button onclick="undefinedFunction()">Buy</button>
        <script>console.error('Payment widget failed to load')</script>
    """)
    page.get_by_role("button", name="Buy").click()
    expect(page.get_by_role("button")).to_be_visible()      # gives the events time to arrive

    print("\ncollected:", js_errors)
    assert len(js_errors) == 2
  • page.on("console", ...) receives every console message; the fixture keeps those of type "error".
  • page.on("pageerror", ...) receives uncaught JavaScript exceptions, such as calling a function that does not exist.
  • Both js_errors and the test receive the same page object: within one test, a function-scoped fixture is created only once and shared.

🔀 Parametrized Fixtures: Desktop and Mobile

A fixture with params runs every test that uses it once per parameter:

📄 conftest.py

# 7. One test, two screen sizes
@pytest.fixture(
    params=[{"width": 1280, "height": 720}, {"width": 390, "height": 844}],
    ids=["desktop", "mobile"],
)
def sized_page(request, new_context) -> Page:
    page = new_context(viewport=request.param).new_page()
    page.goto(SAUCE, wait_until="domcontentloaded")
    return page

📄 tests/test_sizes.py

from playwright.sync_api import Page, expect


def test_login_form_fits(sized_page: Page):
    print(f"\n{sized_page.viewport_size['width']} px wide")
    expect(sized_page.get_by_role("button", name="Login")).to_be_in_viewport()
  • request.param holds the current parameter; ids gives readable names in the test id.
  • new_context(viewport=...) creates a context with that window size, without changing the project’s defaults.

⌨️ Terminal

pytest -q -s tests

🖥️ Output

.
[add_to_cart] teardown, products added in this test: ['Sauce Labs Backpack']
.
[add_to_cart] teardown, products added in this test: ['Sauce Labs Backpack', 'Sauce Labs Bike Light']

[auth_state] logged in once, saved state.json
..
collected: ['console: Payment widget failed to load', 'pageerror: undefinedFunction is not defined']
...
1280 px wide
.
390 px wide
.
9 passed, 1 warning in 36.71s
  • The [add_to_cart] lines come from the fixture’s teardown, after each cart test.
  • The [auth_state] line is printed once, when the first test that needs it runs; the second fast-login test reuses the saved file.

List the generated test ids with --collect-only:

⌨️ Terminal

pytest -q --collect-only tests/test_sizes.py

🖥️ Output

tests/test_sizes.py::test_login_form_fits[desktop-chromium]
tests/test_sizes.py::test_login_form_fits[mobile-chromium]

2 tests collected in 0.00s

Your fixture’s ids come first and pytest-playwright’s browser name second.


⛔ The Scope Rule: ScopeMismatch

A fixture can only use fixtures with the same or a wider scope. page is function-scoped, so a session-scoped fixture cannot use it:

📄 demos/test_scope_error.py

import pytest
from playwright.sync_api import Page


@pytest.fixture(scope="session")
def shared_home(page: Page) -> Page:          # session fixture asking for a function fixture
    page.goto("https://www.saucedemo.com/", wait_until="domcontentloaded")
    return page


def test_uses_shared_home(shared_home: Page):
    assert shared_home.url.startswith("https://www.saucedemo.com")

⌨️ Terminal

pytest -q demos/test_scope_error.py

🖥️ Output

E                                                                        [100%]
=================================== ERRORS ====================================
______________ ERROR at setup of test_uses_shared_home[chromium] ______________
ScopeMismatch: You tried to access the function scoped fixture page with a session scoped request object. Requesting fixture stack:
demos\test_scope_error.py:5:  def shared_home(page: 'Page') -> 'Page'
Requested fixture:
..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:623:  def page(context: 'BrowserContext') -> 'Page'
=========================== short test summary info ===========================
ERROR demos/test_scope_error.py::test_uses_shared_home[chromium] - Failed: Sc...
1 error in 0.03s
  • pytest refuses to start the test and reports a ScopeMismatch error in setup.
  • The fix depends on your goal. To share something expensive across tests, build it from session fixtures (browser, playwright, tmp_path_factory), as auth_state does. To share a page, do not: share its saved state instead.
Your fixture’s scopeMay use
functionEverything: page, context, new_context, browser, playwright
class / modulebrowser, playwright, browser_name and other session fixtures
sessionSession fixtures only: browser, playwright, browser_type, tmp_path_factory, pytestconfig

✅ Good Practices for Playwright Fixtures

  1. Name fixtures after the state they give you: logged_in_page, cart_with_two_items, admin_api.
  2. Assert inside setup fixtures (as logged_in_page does) so a broken setup shows up as a setup error.
  3. Keep tests isolated: share saved state (cookies, tokens) across tests, never a live page or context.
  4. Clean up server-side data after yield; browser data disappears with the context automatically.
  5. **Put shared fixtures in conftest.py** and keep page objects in their own module as the project grows.

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Write a factory fixture login_as that takes a username and password, logs in to SQA Shop with the current page and returns the page.

Show answer
@pytest.fixture
def login_as(page):
    def _login(username="testuser", password="Test@123"):
        page.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
        page.get_by_test_id("login-username").fill(username)
        page.get_by_test_id("login-password").fill(password)
        page.get_by_test_id("login-button").click()
        return page
    return _login

Exercise 2: Write an autouse fixture that collects console errors during a test and fails the test in teardown if any were logged.

Show answer
@pytest.fixture(autouse=True)
def no_console_errors(page):
    errors = []
    page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
    yield
    assert not errors, f"console errors: {errors}"

Exercise 3: Why does this fixture raise ScopeMismatch, and how do you fix it?

@pytest.fixture(scope="session")
def logged_in_page(page): ...
Show answer

page is function-scoped and a session fixture cannot depend on it. Either make logged_in_page function-scoped, or log in once with a session fixture that uses browser (session-scoped), saves storage_state, and let each test create its own context from it.


🧠 MCQ Quiz: Custom Fixtures for Playwright Tests

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Why write custom fixtures for Playwright tests?
  2. Which fixture can a session-scoped login fixture safely use?
  3. What does a page-object fixture return?
  4. What is the benefit of chaining fixtures (e.g. logged_in_page uses login_page)?
  5. Where does clean-up go in a custom fixture?
  6. What error appears when a session fixture requests a function fixture?
  7. How do you run tests once on desktop and once on mobile with one fixture?
  8. What is the advantage of logging in once with storage_state?
  9. How should a fixture signal that setup failed (e.g. login did not work)?
  10. What does a factory fixture allow that a plain fixture does not?

Want a longer, timed test? Take the Module 6 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Can a custom fixture use the page fixture?

Yes, as long as your fixture is function-scoped (the default). The fixture and the test then share the same page object.

🤔 How do I reuse a login across tests without logging in every time?

Log in once in a session-scoped fixture that uses browser, save context.storage_state(path=...), and create each test’s context with new_context(storage_state=path).

🤔 Why is my test reported as an error instead of a failure?

The exception happened in a fixture (setup or teardown), not in the test body. Check the fixture named in the traceback.

🤔 Can I pass arguments to a fixture?

Not directly. Return a function from the fixture (a factory) and call it in the test with the arguments, or use params or indirect parametrization for fixed values.


🏁 Summary

  • Custom fixtures package preparation, such as an opened page object, a logged-in user or products in the cart, into one parameter.
  • Chain fixtures: page → login_page → logged_in_page → add_to_cart.
  • Log in once with a session fixture built on browser, save storage_state, and start each test from it with new_context(storage_state=...).
  • Factory fixtures accept arguments; yield gives you teardown.
  • Listener fixtures, such as js_errors, watch the page during the test.
  • Session fixtures cannot use page: pytest raises ScopeMismatch.

Next, you will control which browsers each test runs on with skip_browser, only_browser and per-test launch options.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

pytest-playwright Built-in Fixtures Explained (page, context, browser and more)

Every Playwright test you have written so far started with a page parameter. Behind that one word, the pytest-playwright plugin builds a chain of fixtures: it starts Playwright, launches a browser, creates a fresh browser context and opens a page, then cleans everything up. In this lesson you will see the whole chain with pytest’s –setup-show, prove that each test is isolated, and use the other built-in fixtures: new_context, browser, browser_name, is_chromium, device, output_path, base_url and the playwright object itself.

📖 What You’ll Learn: the fixture chain from playwright to page, which fixtures are session-scoped and which run per test, watching setup and teardown with –setup-show, how a fresh context isolates cookies and storage, new_context for several users or settings in one test, using browser for contexts you manage yourself, browser_name and the is_chromium, is_firefox and is_webkit flags, browser_channel and device, output_path, base_url, and the playwright fixture for devices and API requests.


🔗 The Fixture Chain Behind page

When a test asks for page, pytest-playwright resolves a chain of fixtures, each built on the one before:

FixtureScopeWhat it gives you
playwrightsessionThe started Playwright object (sync_playwright().start())
browser_typesessionplaywright.chromium, .firefox or .webkit, chosen by --browser
browsersessionOne launched browser, shared by all tests of that browser
new_contextfunctionA function that creates browser contexts and closes them after the test
contextfunctionA fresh BrowserContext for this test, made with new_context()
pagefunctionA new Page in that context

The two scopes are the key idea:

  • Session scope: started once for the whole run. Launching a browser takes time, so all tests share one browser process.
  • Function scope: created for each test. Every test gets a brand-new context, which is like a new incognito window: no cookies, no localStorage, no cache from other tests.

So tests are fast (one browser) and isolated (a fresh context each).

Watching the chain with –setup-show

pytest’s --setup-show option prints every fixture as it is set up (SETUP) and torn down (TEARDOWN), with its scope: S for session, F for function.

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page

URL = "https://sqatools.in/automation-practice-page/"


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto(URL)
    return page

⌨️ Terminal

pytest -q --setup-show tests/test_isolation.py::test_first_visit

🖥️ Output

SETUP    S pytestconfig
SETUP    S delete_output_dir (fixtures used: pytestconfig)
SETUP    S browser_type_launch_args (fixtures used: pytestconfig)
SETUP    S _pw_api_request_contexts (fixtures used: pytestconfig)
SETUP    S playwright (fixtures used: _pw_api_request_contexts)
SETUP    S browser_name (fixtures used: pytestconfig)['chromium']
SETUP    S browser_type (fixtures used: browser_name, playwright)
SETUP    S connect_options
SETUP    S launch_browser (fixtures used: browser_type, browser_type_launch_args, connect_options)
SETUP    S browser (fixtures used: launch_browser)
SETUP    S device (fixtures used: pytestconfig)
SETUP    S base_url (fixtures used: pytestconfig)
SETUP    S _pw_artifacts_folder (fixtures used: pytestconfig)
SETUP    S browser_context_args (fixtures used: _pw_artifacts_folder, base_url, device, playwright, pytestconfig)
        SETUP    F _pw_trace_api_requests
        SETUP    F output_path (fixtures used: pytestconfig)
        SETUP    F _artifacts_recorder (fixtures used: _pw_api_request_contexts, _pw_artifacts_folder, output_path, playwright, pytestconfig)
        SETUP    F new_context (fixtures used: _artifacts_recorder, browser, browser_context_args)
        SETUP    F context (fixtures used: new_context)
        SETUP    F page (fixtures used: context)
        SETUP    F practice (fixtures used: page)
        tests/test_isolation.py::test_first_visit[chromium] (fixtures used: _artifacts_recorder, _pw_api_request_contexts, _pw_artifacts_folder, _pw_trace_api_requests, base_url, browser, browser_context_args, browser_name, browser_type, browser_type_launch_args, connect_options, context, delete_output_dir, device, launch_browser, new_context, output_path, page, playwright, practice, pytestconfig, request) .
        TEARDOWN F practice
        TEARDOWN F page
        TEARDOWN F context
        TEARDOWN F new_context
        TEARDOWN F _artifacts_recorder
        TEARDOWN F output_path
        TEARDOWN F _pw_trace_api_requests
TEARDOWN S browser_context_args
TEARDOWN S _pw_artifacts_folder
TEARDOWN S base_url
TEARDOWN S device
TEARDOWN S browser
TEARDOWN S launch_browser
TEARDOWN S connect_options
TEARDOWN S browser_type
TEARDOWN S browser_name['chromium']
TEARDOWN S playwright
TEARDOWN S _pw_api_request_contexts
TEARDOWN S browser_type_launch_args
TEARDOWN S delete_output_dir
TEARDOWN S pytestconfig
1 passed, 1 warning in 1.90s

Reading the output from top to bottom:

  • The session fixtures (playwright, browser_type, browser, browser_context_args and others) are set up first. Fixtures whose names start with _pw are the plugin’s internal helpers; you never use them directly.
  • browser_name is shown with ['chromium']: pytest-playwright parametrizes every browser test by browser name, which is why test ids end in [chromium].
  • The function fixtures new_context, context and page are created just for this test, then your practice fixture runs on top of page.
  • After the test (the .), teardown runs in reverse order: first the function fixtures, and at the end of the session the browser and Playwright.

🧼 Proving Test Isolation

These two tests run one after the other in the same browser. The first one stores data in the browser; the second checks that none of it is left:

📄 tests/test_isolation.py

from playwright.sync_api import Browser, BrowserContext, Page

SEEN = {}


def test_first_visit(practice: Page, context: BrowserContext, browser: Browser):
    practice.evaluate("localStorage.setItem('cart', '3 items')")
    context.add_cookies([{"name": "session", "value": "abc123", "url": practice.url}])

    SEEN["browser"], SEEN["context"] = browser, context
    print("\nstored:", practice.evaluate("localStorage.getItem('cart')"), "| cookies:", len(context.cookies()))


def test_second_visit(practice: Page, context: BrowserContext, browser: Browser):
    print("\nleft over:", practice.evaluate("localStorage.getItem('cart')"),
          "| cookies named session:", [c for c in context.cookies() if c["name"] == "session"])
    print("same browser:", browser is SEEN["browser"], "| same context:", context is SEEN["context"])
  • SEEN is a plain module-level dictionary used only to compare objects between the two tests.
  • context.add_cookies() adds a cookie; context.cookies() lists the cookies of the context. The count of 7 includes cookies that the live site set itself while loading.
  • localStorage is read and written with page.evaluate(), which runs JavaScript in the page.

Part of the output of pytest -q -s tests (the full run is at the end of this section):

🖥️ Output

stored: 3 items | cookies: 7
.
left over: None | cookies named session: []
same browser: True | same context: False

The second test sees no localStorage value and no session cookie, because it runs in a new context. The browser object, however, is the very same one.

💡 Tip: Isolation is why Playwright tests can run in any order and in parallel. If one of your tests only passes after another test has run, it secretly depends on that test’s state: fix it with a fixture that sets up what it needs.


👥 new_context: Several Users in One Test

Some scenarios need two independent sessions at once: a buyer and a seller, an admin and a user, a chat between two people. The new_context fixture is a function: each call creates another context, using the same settings as context (browser_context_args), plus any options you pass.

📄 tests/test_new_context.py

from playwright.sync_api import Page


def test_two_users(new_context):
    alice = new_context().new_page()
    bob = new_context(locale="de-DE", viewport={"width": 800, "height": 600}).new_page()

    alice.goto("https://sqatools.in/automation-practice-page/")
    bob.goto("https://sqatools.in/automation-practice-page/")
    alice.evaluate("localStorage.setItem('user', 'alice')")

    print("\nalice sees:", alice.evaluate("localStorage.getItem('user')"))
    print("bob sees  :", bob.evaluate("localStorage.getItem('user')"))
    print("bob locale:", bob.evaluate("navigator.language"), "| bob viewport:", bob.viewport_size)


def test_page_and_extra_context(page: Page, new_context):
    # page uses one context; new_context() makes a second, independent one
    other = new_context().new_page()
    print("\ncontexts in the browser:", len(page.context.browser.contexts))
    assert page.context is not other.context
  • Each new_context() call returns a new, isolated BrowserContext.
  • Options passed to the call, such as locale or viewport, are added to the configured browser_context_args for that context only.
  • You do not close these contexts yourself: the fixture closes all of them after the test. They also get the plugin’s tracing, video and screenshot handling.

🌐 browser: Contexts You Manage Yourself

You can also call browser.new_context() directly. The difference: such a context does not use browser_context_args, does not get the plugin’s artifacts, and you must close it.

📄 tests/test_browser_fixture.py

from playwright.sync_api import Browser


def test_manual_context(browser: Browser):
    context = browser.new_context(java_script_enabled=False)
    try:
        page = context.new_page()
        page.goto("https://sqatools.in/automation-practice-page/")
        print("\nbrowser:", browser.browser_type.name, browser.version.split(".")[0], "| JS enabled:", False)
    finally:
        context.close()
  • try / finally makes sure the context is closed even if the test fails.
  • Prefer new_context in tests. Use browser.new_context() when you deliberately want a context without the project’s default settings.

⌨️ Terminal

pytest -q -s tests

🖥️ Output

browser: chromium 156 | JS enabled: False
.
stored: 3 items | cookies: 7
.
left over: None | cookies named session: []
same browser: True | same context: False
.
alice sees: alice
bob sees  : None
bob locale: de-DE | bob viewport: {'width': 800, 'height': 600}
.
contexts in the browser: 2
.
5 passed, 1 warning in 8.88s

🧭 Information Fixtures: browser_name, is_*, channel and device

These session fixtures tell a test where it runs:

FixtureValue
browser_name"chromium", "firefox" or "webkit"
is_chromium, is_firefox, is_webkitTrue or False
browser_channelThe --browser-channel value, such as "chrome", or None
deviceThe --device value, such as "iPhone 15", or None
output_pathThis test’s artifact folder inside --output (function scope)

📄 info/test_where_am_i.py

from playwright.sync_api import Page


def test_where_am_i(page: Page, browser_name, is_webkit, browser_channel, device, output_path):
    print(f"\nbrowser_name={browser_name} is_webkit={is_webkit} channel={browser_channel} device={device}")
    print("viewport:", page.viewport_size, "| iPhone user agent:", "iPhone" in page.evaluate("navigator.userAgent"))
    print("output_path ends with:", output_path.replace("\\", "/").split("/")[-1])

⌨️ Terminal

pytest -q -s info --browser firefox --device "iPhone 15"

🖥️ Output

browser_name=firefox is_webkit=False channel=None device=iPhone 15
viewport: {'width': 393, 'height': 659} | iPhone user agent: True
output_path ends with: info-test-where-am-i-py-test-where-am-i-firefox
.
1 passed, 1 warning in 2.00s
  • --device "iPhone 15" applies the device’s viewport (393 x 659), user agent and touch support to every context, through browser_context_args.
  • The iPhone descriptor names WebKit as its default browser, but --browser decides which browser actually runs. Here Firefox ran with the iPhone viewport and user agent. For the most realistic iPhone emulation, run such tests on WebKit.
  • output_path is a folder name built from the test id. Nothing is written there unless an artifact is kept.

Now run on two browsers:

⌨️ Terminal

pytest -q -s info --browser chromium --browser webkit

🖥️ Output

browser_name=chromium is_webkit=False channel=None device=None
viewport: {'width': 1280, 'height': 720} | iPhone user agent: False
output_path ends with: info-test-where-am-i-py-test-where-am-i-chromium
.
browser_name=webkit is_webkit=True channel=None device=None
viewport: {'width': 1280, 'height': 720} | iPhone user agent: False
output_path ends with: info-test-where-am-i-py-test-where-am-i-webkit
.
2 passed, 1 warning in 0.72s

Each --browser adds one parametrized copy of every test, so the test ran twice with a different browser_name.


🏠 base_url: Short URLs in Tests

The base_url fixture holds the value of --base-url (or base_url in pytest.ini, or the PYTEST_BASE_URL environment variable). pytest-playwright passes it to every context, so page.goto() accepts paths:

📄 base/test_base_url.py

from playwright.sync_api import Page, expect


def test_relative_goto(page: Page, base_url):
    print("\nbase_url:", base_url)
    page.goto("/automation-practice-page/")                 # resolved against base_url
    expect(page).to_have_url("https://sqatools.in/automation-practice-page/")

⌨️ Terminal

pytest -q -s base --base-url https://sqatools.in

🖥️ Output

base_url: https://sqatools.in
.
1 passed, 1 warning in 2.46s

📝 Note: The PytestRemovedIn10Warning you have seen in every run’s summary comes from this fixture: pytest-playwright 0.10 defines base_url as a method of a helper class, which pytest 9.2 reports as deprecated. It does not affect your tests. Silence it with a filterwarnings line in pytest.ini if it bothers you, as shown in Module 3.


🎭 The playwright Fixture

The session-scoped playwright fixture is the same object you get from sync_playwright().start(). Two things you will use it for:

📄 pw/test_playwright_fixture.py

def test_device_list(playwright):
    iphone = playwright.devices["iPhone 15"]               # a device descriptor (a dict)
    print(iphone["viewport"], iphone["default_browser_type"])

def test_api(playwright):
    api = playwright.request.new_context(base_url="https://sqatools.in")
    response = api.get("/automation-practice-page/")
    assert response.ok
    api.dispose()
  • playwright.devices contains the device descriptors used by --device. You can pass one to new_context(**playwright.devices["Pixel 7"]).
  • playwright.request creates API clients without a browser. Module 9 covers API testing in detail.

📋 All Built-in Fixtures at a Glance

FixtureScopeTypical use
pagefunctionAlmost every UI test
contextfunctionCookies, permissions, routes, a second page in the same session
new_contextfunctionSeveral independent users or per-test context options
browsersessionContexts without the default settings
browser_type, launch_browsersessionLaunching another browser yourself
playwrightsessionDevices, API request contexts
browser_context_argssessionOverride to change context settings (Lesson 6)
browser_type_launch_argssessionOverride to change launch options (headless, args, channel)
connect_optionssessionOverride to connect to a remote browser server
browser_name, browser_channel, devicesessionWhere the test runs
is_chromium, is_firefox, is_webkitsessionBrowser-specific branches
output_pathfunctionThis test’s artifact folder
base_urlsessionThe --base-url value

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Write a test that uses new_context to open the SQA Shop as two users at once: a guest and a logged-in shopper, and checks both headers.

Show answer
def test_two_users(new_context):
    guest = new_context().new_page()
    member = new_context().new_page()
    guest.goto("https://sqatools.in/dummy-ecommerce-website/")
    member.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
    member.get_by_test_id("login-username").fill("testuser")
    member.get_by_test_id("login-password").fill("Test@123")
    member.get_by_test_id("login-button").click()
    expect(guest.get_by_test_id("account-button")).to_contain_text("Login")
    expect(member.get_by_test_id("account-button")).to_contain_text("Hi, Test")

Contexts created by new_context are closed automatically after the test.

Exercise 2: Print the current browser and the folder where this test’s artifacts go.

Show answer
def test_info(browser_name, output_path):
    print(browser_name, output_path)

Exercise 3: Which command shows the fixture chain (playwright → browser_type → browser → context → page) being set up and torn down?

Show answer
pytest tests/test_home.py --setup-show

🧠 MCQ Quiz: pytest-playwright Built-in Fixtures

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which fixture is session-scoped?
  2. Which fixture gives a fresh context per test?
  3. What does new_context return?
  4. What is browser_name?
  5. Which fixture holds options passed to browser.new_context()?
  6. What does output_path provide?
  7. Why does each test get a new context instead of sharing one?
  8. Which fixture gives access to playwright.devices and playwright.request?
  9. How do you see which fixtures pytest-playwright provides?
  10. Where does the base_url fixture come from?

Want a longer, timed test? Take the Module 6 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Is the browser restarted for every test?

No. The browser fixture is session-scoped, so one browser is launched per browser type for the whole run (per worker when you use pytest-xdist). Each test gets a fresh context instead, which is fast and fully isolated.

🤔 Can I make the page fixture shared between tests to save time?

You could write your own session-scoped page fixture, but tests would then share cookies and state and depend on each other’s order. Keep the per-test context; to save login time, reuse a saved login state instead (Module 8).

🤔 What is the difference between context and new_context?

context is one ready-made context for the test. new_context is a function that creates as many extra contexts as you need, with optional per-context settings. All of them are closed automatically after the test.

🤔 Why do all my test names end with [chromium]?

pytest-playwright parametrizes browser tests by browser_name. The suffix shows which browser ran that copy of the test, which matters when you pass several --browser options.


🏁 Summary

  • page sits on a chain: playwright → browser_type → browser (session) → new_context → context → page (per test).
  • One shared browser makes runs fast; a fresh context per test keeps them isolated.
  • --setup-show reveals which fixtures run and in which scope.
  • new_context creates extra isolated contexts with optional settings and closes them for you.
  • browser.new_context() skips the project settings and must be closed by you.
  • browser_name, is_*, browser_channel, device, output_path and base_url tell a test where and how it runs.

Next, you will write your own fixtures on top of these: page objects, logged-in pages, test data with cleanup and fixture factories.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page