re.Pattern

What re.compile gives you. It carries the source pattern, the effective flags, the group count and the name → number map, and has the same search/match/fullmatch/findall/finditer/sub/subn/split methods as the module — with extra pos/endpos arguments.

re classPython 3 (all)Live demo
Common call
pat = re.compile(r'(?P<key>\w+)=(\d+)')
Returns
pat.pattern, pat.flags, pat.groups == 2, pat.groupindex == {"key": 1}
Replaces
passing the same pattern string around
Watch out
Cannot be created with re.Pattern(...) — call re.compile
class re.Pattern
→ re.Pattern

Demo

Live evaluation
pattern, flags, groups and groupindex of a compiled pattern.
Try:
Inputs
patternstra regular expression
Code
import re
p = re.compile('\\d+')
(p.pattern, p.flags, p.groups, p.groupindex)
Result
('\\d+', 32, 0, {})

flags always includes 32 (re.UNICODE) for a str pattern; (?ix) adds 2 and 64, so the total is 98. Non-capturing (?:...) groups are not counted in groups. iter(sc.match, None) calls scanner.match() until it returns None — at the first character no token can start, so "1,2,x,3" stops before the x.

Attributes

AttributeTypeMeaning
patternstr | bytesThe pattern string it was compiled from
flagsintEffective flags: those passed, inline ones, and re.UNICODE (32) for str patterns
groupsintNumber of capturing groups
groupindexmappingNamed group → group number (a read-only mappingproxy; an empty dict when there are no names)
scanner(string, pos=0, endpos=…)SRE_ScannerUndocumented helper: an object whose match() / search() continue from the previous match — what finditer uses internally

Common patterns

Type hints
re.Pattern is generic since 3.9.
import re
def find_ids(pat: re.Pattern[str], text: str) -> list[str]:
    return pat.findall(text)
Accept a string or a compiled pattern
re.compile returns an already-compiled Pattern unchanged.
import re
def search_all(pattern, texts):
    pat = re.compile(pattern)  # works for str and re.Pattern
    return [pat.search(t) for t in texts]
Map a group name to its number
groupindex is read-only; copy it with dict() if you need a dict.
import re
names = dict(pat.groupindex)
number_of = names.get

Examples

1. The type of compile()
import re type(re.compile('a'))
Returns
<class 're.Pattern'>
2. pattern and groups
import re p = re.compile(r'(a)(?P<n>b)(?:c)') (p.pattern, p.groups)
Returns
('(a)(?P<n>b)(?:c)', 2)
3. groupindex
import re re.compile(r'(a)(?P<n>b)').groupindex
Returns
mappingproxy({'n': 2})
4. No names: empty dict
import re re.compile(r'(a)').groupindex
Returns
{}
5. flags includes UNICODE
import re (re.compile('a').flags, re.compile('a', re.I).flags, re.compile('a', re.A).flags)
Returns
(32, 34, 256)
6. Methods take pos/endpos
import re re.compile(r'\d').findall('0123456', 2, 5)
Returns
['2', '3', '4']
7. scanner().search()
import re sc = re.compile(r'\d').scanner('a1b2') (sc.search(), sc.search(), sc.search())
Returns
(<re.Match object; span=(1, 2), match='1'>, <re.Match object; span=(3, 4), match='2'>, None)

Pitfalls

1. Trying to instantiate re.Pattern
The class exists for isinstance checks and type hints only.
re.Pattern(...)
import re
re.Pattern(r'\d+')
TypeError: cannot create 're.Pattern' instances
re.compile(...)
import re
isinstance(re.compile(r'\d+'), re.Pattern)
True
2. Modifying groupindex
It is a read-only view.
assign
import re
p = re.compile(r'(?P<a>x)')
p.groupindex['b'] = 2
TypeError: 'mappingproxy' object does not support item assignment
dict copy
import re
p = re.compile(r'(?P<a>x)')
d = dict(p.groupindex)
d['b'] = 2
d
{'a': 1, 'b': 2}

When to use

Use it
  • Inspecting a pattern: how many groups, which names, which flags
  • Type hints (re.Pattern[str]) and isinstance checks
  • pos/endpos arguments that the module functions do not have
Reach for something else
  • Relying on scanner() in library code — it is undocumented
  • Comparing Pattern objects to test for "same regex" — compare .pattern and .flags

Notes

CPython impl
PatternObject in Modules/_sre/_sre.c; the attributes are read-only members, scanner() returns an SRE_Scanner used by finditer
Equality
Two Pattern objects compare equal when they have the same pattern string and flags
Generic
re.Pattern[str] / re.Pattern[bytes] in annotations since Python 3.9
Copy
copy.copy() and copy.deepcopy() return the same object (3.7+) — patterns are immutable

FAQ

Read .pattern: re.compile(r'\d+').pattern is '\\d+' (the backslash shown doubled in the repr).