Skip to content

QR Code API Reference

Auto-generated API documentation for the QR code module.

qr

QR Code generator library (Python).

Part of zerodep: https://github.com/Oaklight/zerodep Copyright (c) 2026 Peng Ding. MIT License.

Originally derived from Project Nayuki's QR Code generator (MIT License), substantially refactored for the zerodep project: Copyright (c) Project Nayuki https://www.nayuki.io/page/qr-code-generator-library

QrCode

A QR Code symbol, which is a type of two-dimension barcode. Invented by Denso Wave and described in the ISO/IEC 18004 standard. Instances of this class represent an immutable square grid of dark and light cells. The class provides static factory functions to create a QR Code from text or binary data. The class covers the QR Code Model 2 specification, supporting all versions (sizes) from 1 to 40, all 4 error correction levels, and 4 character encoding modes.

Ways to create a QR Code object: - High level: Take the payload data and call QrCode.encode_text() or QrCode.encode_binary(). - Mid level: Custom-make the list of segments and call QrCode.encode_segments(). - Low level: Custom-make the array of data codeword bytes (including segment headers and final padding, excluding error correction codewords), supply the appropriate version number, and call the QrCode() constructor. (Note that all ways require supplying the desired error correction level.)

Source code in qr/qr.py
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
class QrCode:
    """A QR Code symbol, which is a type of two-dimension barcode.
    Invented by Denso Wave and described in the ISO/IEC 18004 standard.
    Instances of this class represent an immutable square grid of dark and light cells.
    The class provides static factory functions to create a QR Code from text or binary data.
    The class covers the QR Code Model 2 specification, supporting all versions (sizes)
    from 1 to 40, all 4 error correction levels, and 4 character encoding modes.

    Ways to create a QR Code object:
    - High level: Take the payload data and call QrCode.encode_text() or QrCode.encode_binary().
    - Mid level: Custom-make the list of segments and call QrCode.encode_segments().
    - Low level: Custom-make the array of data codeword bytes (including
      segment headers and final padding, excluding error correction codewords),
      supply the appropriate version number, and call the QrCode() constructor.
    (Note that all ways require supplying the desired error correction level.)"""

    # ---- Static factory functions (high level) ----

    @staticmethod
    def encode_text(text: str, ecl: QrCode.Ecc) -> QrCode:
        """Returns a QR Code representing the given Unicode text string at the given error correction level.
        As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
        Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
        QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
        ecl argument if it can be done without increasing the version."""
        segs: list[QrSegment] = QrSegment.make_segments(text)
        return QrCode.encode_segments(segs, ecl)

    @staticmethod
    def encode_binary(data: Union[bytes, Sequence[int]], ecl: QrCode.Ecc) -> QrCode:
        """Returns a QR Code representing the given binary data at the given error correction level.
        This function always encodes using the binary segment mode, not any text mode. The maximum number of
        bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
        The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version."""
        return QrCode.encode_segments([QrSegment.make_bytes(data)], ecl)

    # ---- Static factory functions (mid level) ----

    @staticmethod
    def encode_segments(
        segs: Sequence[QrSegment],
        ecl: QrCode.Ecc,
        minversion: int = 1,
        maxversion: int = 40,
        mask: int = -1,
        boostecl: bool = True,
    ) -> QrCode:
        """Returns a QR Code representing the given segments with the given encoding parameters.
        The smallest possible QR Code version within the given range is automatically
        chosen for the output. Iff boostecl is true, then the ECC level of the result
        may be higher than the ecl argument if it can be done without increasing the
        version. The mask number is either between 0 to 7 (inclusive) to force that
        mask, or -1 to automatically choose an appropriate mask (which may be slow).
        This function allows the user to create a custom sequence of segments that switches
        between modes (such as alphanumeric and byte) to encode text in less space.
        This is a mid-level API; the high-level API is encode_text() and encode_binary()."""

        if not (
            QrCode.MIN_VERSION <= minversion <= maxversion <= QrCode.MAX_VERSION
        ) or not (-1 <= mask <= 7):
            raise ValueError("Invalid value")

        # Find the minimal version number to use
        for version in range(minversion, maxversion + 1):
            datacapacitybits: int = (
                QrCode._get_num_data_codewords(version, ecl) * 8
            )  # Number of data bits available
            datausedbits: int | None = QrSegment.get_total_bits(segs, version)
            if (datausedbits is not None) and (datausedbits <= datacapacitybits):
                break  # This version number is found to be suitable
            if (
                version >= maxversion
            ):  # All versions in the range could not fit the given data
                msg: str = "Segment too long"
                if datausedbits is not None:
                    msg = f"Data length = {datausedbits} bits, Max capacity = {datacapacitybits} bits"
                raise DataTooLongError(msg)
        assert datausedbits is not None

        # Increase the error correction level while the data still fits in the current version number
        for newecl in (
            QrCode.Ecc.MEDIUM,
            QrCode.Ecc.QUARTILE,
            QrCode.Ecc.HIGH,
        ):  # From low to high
            if boostecl and (
                datausedbits <= QrCode._get_num_data_codewords(version, newecl) * 8
            ):
                ecl = newecl

        # Concatenate all segments to create the data bit string
        bb = _BitBuffer()
        for seg in segs:
            bb.append_bits(seg.get_mode().get_mode_bits(), 4)
            bb.append_bits(
                seg.get_num_chars(), seg.get_mode().num_char_count_bits(version)
            )
            bb.extend(seg._bitdata)
        assert len(bb) == datausedbits

        # Add terminator and pad up to a byte if applicable
        datacapacitybits = QrCode._get_num_data_codewords(version, ecl) * 8
        assert len(bb) <= datacapacitybits
        bb.append_bits(0, min(4, datacapacitybits - len(bb)))
        bb.append_bits(
            0, -len(bb) % 8
        )  # Note: Python's modulo on negative numbers behaves better than C family languages
        assert len(bb) % 8 == 0

        # Pad with alternating bytes until data capacity is reached
        for padbyte in itertools.cycle((0xEC, 0x11)):
            if len(bb) >= datacapacitybits:
                break
            bb.append_bits(padbyte, 8)

        # Pack bits into bytes in big endian
        datacodewords = bb.pack_to_bytes()

        # Create the QR Code object
        return QrCode(version, ecl, datacodewords, mask)

    # ---- Private fields ----

    # The version number of this QR Code, which is between 1 and 40 (inclusive).
    # This determines the size of this barcode.
    _version: int

    # The width and height of this QR Code, measured in modules, between
    # 21 and 177 (inclusive). This is equal to version * 4 + 17.
    _size: int

    # The error correction level used in this QR Code.
    _errcorlvl: QrCode.Ecc

    # The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
    # Even if a QR Code is created with automatic masking requested (mask = -1),
    # the resulting object still has a mask value between 0 and 7.
    _mask: int

    # The modules of this QR Code (0 = light, 1 = dark).
    # Stored as list of bytearrays for compact memory and fast iteration.
    # Immutable after constructor finishes. Accessed through get_module().
    _modules: list[bytearray]

    # Indicates function modules that are not subjected to masking.
    # Stored as list of bytearrays. Discarded when constructor finishes.
    _isfunction: list[bytearray]

    # ---- Constructor (low level) ----

    def __init__(
        self,
        version: int,
        errcorlvl: QrCode.Ecc,
        datacodewords: Union[bytes, Sequence[int]],
        msk: int,
    ) -> None:
        """Creates a new QR Code with the given version number,
        error correction level, data codeword bytes, and mask number.
        This is a low-level API that most users should not use directly.
        A mid-level API is the encode_segments() function."""

        # Check scalar arguments and set fields
        if not (QrCode.MIN_VERSION <= version <= QrCode.MAX_VERSION):
            raise ValueError("Version value out of range")
        if not (-1 <= msk <= 7):
            raise ValueError("Mask value out of range")

        self._version = version
        self._size = version * 4 + 17
        self._errcorlvl = errcorlvl

        # Initialize both grids to be size*size arrays of 0 (light)
        self._modules = [
            bytearray(self._size) for _ in range(self._size)
        ]  # Initially all light
        self._isfunction = [bytearray(self._size) for _ in range(self._size)]

        # Compute ECC, draw modules
        self._draw_function_patterns()
        allcodewords: bytes = self._add_ecc_and_interleave(bytearray(datacodewords))
        self._draw_codewords(allcodewords)

        # Do masking
        if msk == -1:  # Automatically choose best mask
            # Precompute mask grids to avoid per-pixel arithmetic and
            # isfunction checks during the 8-mask evaluation loop
            mask_grids = _build_mask_grids(self._isfunction, self._size)
            minpenalty: int = 1 << 32
            for i in range(8):
                _apply_precomputed_mask(self._modules, mask_grids[i], self._size)
                self._draw_format_bits(i)
                penalty = self._get_penalty_score()
                if penalty < minpenalty:
                    msk = i
                    minpenalty = penalty
                _apply_precomputed_mask(
                    self._modules, mask_grids[i], self._size
                )  # Undoes the mask due to XOR
            assert 0 <= msk <= 7
            self._mask = msk
            _apply_precomputed_mask(self._modules, mask_grids[msk], self._size)
        else:
            self._mask = msk
            self._apply_mask(msk)  # Apply the specified mask
        self._draw_format_bits(msk)  # Overwrite old format bits

        del self._isfunction

    # ---- Accessor methods ----

    def get_version(self) -> int:
        """Returns this QR Code's version number, in the range [1, 40]."""
        return self._version

    def get_size(self) -> int:
        """Returns this QR Code's size, in the range [21, 177]."""
        return self._size

    def get_error_correction_level(self) -> QrCode.Ecc:
        """Returns this QR Code's error correction level."""
        return self._errcorlvl

    def get_mask(self) -> int:
        """Returns this QR Code's mask, in the range [0, 7]."""
        return self._mask

    def get_module(self, x: int, y: int) -> bool:
        """Returns the color of the module (pixel) at the given coordinates, which is False
        for light or True for dark. The top left corner has the coordinates (x=0, y=0).
        If the given coordinates are out of bounds, then False (light) is returned."""
        return (
            (0 <= x < self._size) and (0 <= y < self._size) and self._modules[y][x] != 0
        )

    # ---- Private helper methods for constructor: Drawing function modules ----

    def _draw_function_patterns(self) -> None:
        """Reads this object's version field, and draws and marks all function modules."""
        # Draw horizontal and vertical timing patterns
        for i in range(self._size):
            self._set_function_module(6, i, i % 2 == 0)
            self._set_function_module(i, 6, i % 2 == 0)

        # Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
        self._draw_finder_pattern(3, 3)
        self._draw_finder_pattern(self._size - 4, 3)
        self._draw_finder_pattern(3, self._size - 4)

        # Draw numerous alignment patterns
        alignpatpos: list[int] = self._get_alignment_pattern_positions()
        numalign: int = len(alignpatpos)
        skips: Sequence[tuple[int, int]] = (
            (0, 0),
            (0, numalign - 1),
            (numalign - 1, 0),
        )
        for i in range(numalign):
            for j in range(numalign):
                if (i, j) not in skips:  # Don't draw on the three finder corners
                    self._draw_alignment_pattern(alignpatpos[i], alignpatpos[j])

        # Draw configuration data
        self._draw_format_bits(
            0
        )  # Dummy mask value; overwritten later in the constructor
        self._draw_version()

    def _draw_format_bits(self, mask: int) -> None:
        """Draws two copies of the format bits (with its own error correction code)
        based on the given mask and this object's error correction level field."""
        # Calculate error correction code and pack bits
        data: int = (
            self._errcorlvl.formatbits << 3 | mask
        )  # errCorrLvl is uint2, mask is uint3
        rem: int = data
        for _ in range(10):
            rem = (rem << 1) ^ ((rem >> 9) * 0x537)
        bits: int = (data << 10 | rem) ^ 0x5412  # uint15
        assert bits >> 15 == 0

        # Inline module writes to avoid _set_function_module call overhead.
        # These cells are all function modules, so isfunction is already set.
        modules = self._modules
        size = self._size

        # Draw first copy
        for i in range(0, 6):
            modules[i][8] = (bits >> i) & 1
        modules[7][8] = (bits >> 6) & 1
        modules[8][8] = (bits >> 7) & 1
        modules[8][7] = (bits >> 8) & 1
        for i in range(9, 15):
            modules[8][14 - i] = (bits >> i) & 1

        # Draw second copy
        for i in range(0, 8):
            modules[8][size - 1 - i] = (bits >> i) & 1
        for i in range(8, 15):
            modules[size - 15 + i][8] = (bits >> i) & 1
        modules[size - 8][8] = 1  # Always dark

    def _draw_version(self) -> None:
        """Draws two copies of the version bits (with its own error correction code),
        based on this object's version field, iff 7 <= version <= 40."""
        if self._version < 7:
            return

        # Calculate error correction code and pack bits
        rem: int = self._version  # version is uint6, in the range [7, 40]
        for _ in range(12):
            rem = (rem << 1) ^ ((rem >> 11) * 0x1F25)
        bits: int = self._version << 12 | rem  # uint18
        assert bits >> 18 == 0

        # Draw two copies
        for i in range(18):
            bit: int = _get_bit(bits, i)
            a: int = self._size - 11 + i % 3
            b: int = i // 3
            self._set_function_module(a, b, bit)
            self._set_function_module(b, a, bit)

    def _draw_finder_pattern(self, x: int, y: int) -> None:
        """Draws a 9*9 finder pattern including the border separator,
        with the center module at (x, y). Modules can be out of bounds."""
        for dy in range(-4, 5):
            for dx in range(-4, 5):
                xx, yy = x + dx, y + dy
                if (0 <= xx < self._size) and (0 <= yy < self._size):
                    # Chebyshev/infinity norm
                    self._set_function_module(
                        xx, yy, max(abs(dx), abs(dy)) not in (2, 4)
                    )

    def _draw_alignment_pattern(self, x: int, y: int) -> None:
        """Draws a 5*5 alignment pattern, with the center module
        at (x, y). All modules must be in bounds."""
        for dy in range(-2, 3):
            for dx in range(-2, 3):
                self._set_function_module(x + dx, y + dy, max(abs(dx), abs(dy)) != 1)

    def _set_function_module(self, x: int, y: int, isdark: int | bool) -> None:
        """Sets the color of a module and marks it as a function module.
        Only used by the constructor. Coordinates must be in bounds."""
        self._modules[y][x] = 1 if isdark else 0
        self._isfunction[y][x] = 1

    # ---- Private helper methods for constructor: Codewords and masking ----

    def _add_ecc_and_interleave(self, data: bytearray) -> bytes:
        """Returns a new byte string representing the given data with the appropriate error correction
        codewords appended to it, based on this object's version and error correction level."""
        version: int = self._version
        assert len(data) == QrCode._get_num_data_codewords(version, self._errcorlvl)

        # Calculate parameter numbers
        numblocks: int = QrCode._NUM_ERROR_CORRECTION_BLOCKS[self._errcorlvl.ordinal][
            version
        ]
        blockecclen: int = QrCode._ECC_CODEWORDS_PER_BLOCK[self._errcorlvl.ordinal][
            version
        ]
        rawcodewords: int = QrCode._get_num_raw_data_modules(version) // 8
        numshortblocks: int = numblocks - rawcodewords % numblocks
        shortblocklen: int = rawcodewords // numblocks

        # Split data into blocks and append ECC to each block
        blocks: list[bytes] = []
        rsdiv: bytes = QrCode._reed_solomon_compute_divisor(blockecclen)
        k: int = 0
        for i in range(numblocks):
            dat: bytearray = data[
                k : k + shortblocklen - blockecclen + (0 if i < numshortblocks else 1)
            ]
            k += len(dat)
            ecc: bytes = QrCode._reed_solomon_compute_remainder(bytes(dat), rsdiv)
            if i < numshortblocks:
                dat.append(0)
            blocks.append(bytes(dat) + ecc)
        assert k == len(data)

        # Interleave (not concatenate) the bytes from every block into a single sequence
        result = bytearray()
        for i in range(len(blocks[0])):
            for j, blk in enumerate(blocks):
                # Skip the padding byte in short blocks
                if (i != shortblocklen - blockecclen) or (j >= numshortblocks):
                    result.append(blk[i])
        assert len(result) == rawcodewords
        return bytes(result)

    def _draw_codewords(self, data: bytes) -> None:
        """Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
        data area of this QR Code. Function modules need to be marked off before this is called."""
        assert len(data) == QrCode._get_num_raw_data_modules(self._version) // 8

        i: int = 0  # Bit index into the data
        datalen8 = len(data) * 8
        modules = self._modules
        isfunction = self._isfunction
        size = self._size
        # Do the funny zigzag scan
        for right in range(
            size - 1, 0, -2
        ):  # Index of right column in each column pair
            if right <= 6:
                right -= 1
            for vert in range(size):  # Vertical counter
                for j in range(2):
                    x: int = right - j  # Actual x coordinate
                    upward: bool = (right + 1) & 2 == 0
                    y: int = (
                        (size - 1 - vert) if upward else vert
                    )  # Actual y coordinate
                    if (not isfunction[y][x]) and (i < datalen8):
                        modules[y][x] = (data[i >> 3] >> (7 - (i & 7))) & 1
                        i += 1
                    # If this QR Code has any remainder bits (0 to 7), they were assigned as
                    # 0/false/light by the constructor and are left unchanged by this method
        assert i == datalen8

    def _apply_mask(self, mask: int) -> None:
        """XORs the codeword modules in this QR Code with the given mask pattern.

        Used when a specific mask is requested (not auto-select). For auto-select,
        precomputed mask grids are used instead for better performance.

        The function modules must be marked and the codeword bits must be drawn
        before masking. Due to the arithmetic of XOR, calling _apply_mask() with
        the same mask value a second time will undo the mask. A final well-formed
        QR Code needs exactly one (not zero, two, etc.) mask applied.
        """
        if not (0 <= mask <= 7):
            raise ValueError("Mask value out of range")
        grids = _build_mask_grids(self._isfunction, self._size)
        _apply_precomputed_mask(self._modules, grids[mask], self._size)

    def _get_penalty_score(self) -> int:
        """Calculates and returns the penalty score based on state of this QR Code's current modules.

        Merges all four penalty rules into a single grid traversal to minimize
        iteration overhead. Maintains per-column state to compute vertical
        penalties during the row-major pass.

        This is used by the automatic mask choice algorithm to find the mask
        pattern that yields the lowest score.
        """
        result: int = _compute_penalty(
            self._modules,
            self._size,
            QrCode._PENALTY_N1,
            QrCode._PENALTY_N2,
            QrCode._PENALTY_N3,
            QrCode._PENALTY_N4,
        )
        assert (
            0 <= result <= 2568888
        )  # Non-tight upper bound based on default values of PENALTY_N1, ..., N4
        return result

    # ---- Private helper functions ----

    def _get_alignment_pattern_positions(self) -> list[int]:
        """Returns an ascending list of positions of alignment patterns for this version number.
        Each position is in the range [0,177), and are used on both the x and y axes.
        This could be implemented as lookup table of 40 variable-length lists of integers."""
        if self._version == 1:
            return []
        else:
            numalign: int = self._version // 7 + 2
            step: int = (self._version * 8 + numalign * 3 + 5) // (numalign * 4 - 4) * 2
            result: list[int] = [
                (self._size - 7 - i * step) for i in range(numalign - 1)
            ] + [6]
            return list(reversed(result))

    @staticmethod
    def _get_num_raw_data_modules(ver: int) -> int:
        """Returns the number of data bits that can be stored in a QR Code of the given version number, after
        all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
        The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table."""
        if not (QrCode.MIN_VERSION <= ver <= QrCode.MAX_VERSION):
            raise ValueError("Version number out of range")
        result: int = (16 * ver + 128) * ver + 64
        if ver >= 2:
            numalign: int = ver // 7 + 2
            result -= (25 * numalign - 10) * numalign - 55
            if ver >= 7:
                result -= 36
        assert 208 <= result <= 29648
        return result

    @staticmethod
    def _get_num_data_codewords(ver: int, ecl: QrCode.Ecc) -> int:
        """Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
        QR Code of the given version number and error correction level, with remainder bits discarded.
        This stateless pure function could be implemented as a (40*4)-cell lookup table."""
        return (
            QrCode._get_num_raw_data_modules(ver) // 8
            - QrCode._ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver]
            * QrCode._NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]
        )

    @staticmethod
    def _reed_solomon_compute_divisor(degree: int) -> bytes:
        """Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
        implemented as a lookup table over all possible parameter values, instead of as an algorithm."""
        if not (1 <= degree <= 255):
            raise ValueError("Degree out of range")
        # Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
        # For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
        result = bytearray([0] * (degree - 1) + [1])  # Start off with the monomial x^0

        # Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
        # and drop the highest monomial term which is always 1x^degree.
        # Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
        root: int = 1
        gf_mul = _GF_MUL
        for _ in range(degree):  # Unused variable i
            # Multiply the current product by (x - r^i)
            root_row = gf_mul[root]
            for j in range(degree):
                result[j] = root_row[result[j]]
                if j + 1 < degree:
                    result[j] ^= result[j + 1]
            root = gf_mul[root][0x02]
        return bytes(result)

    @staticmethod
    def _reed_solomon_compute_remainder(data: bytes, divisor: bytes) -> bytes:
        """Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials."""
        result = bytearray([0] * len(divisor))
        gf_mul = _GF_MUL
        for b in data:  # Polynomial division
            factor: int = b ^ result[0]
            del result[0]
            result.append(0)
            if factor != 0:
                factor_row = gf_mul[factor]
                for i, coef in enumerate(divisor):
                    result[i] ^= factor_row[coef]
        return bytes(result)

    @staticmethod
    def _reed_solomon_multiply(x: int, y: int) -> int:
        """Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
        are unsigned 8-bit integers. Uses precomputed lookup table for O(1) performance."""
        return _GF_MUL[x][y]

    # ---- Constants and tables ----

    MIN_VERSION: int = (
        1  # The minimum version number supported in the QR Code Model 2 standard
    )
    MAX_VERSION: int = (
        40  # The maximum version number supported in the QR Code Model 2 standard
    )

    # For use in _get_penalty_score(), when evaluating which mask is best.
    _PENALTY_N1: int = 3
    _PENALTY_N2: int = 3
    _PENALTY_N3: int = 40
    _PENALTY_N4: int = 10

    _ECC_CODEWORDS_PER_BLOCK: Sequence[Sequence[int]] = (
        # Version: (note that index 0 is for padding, and is set to an illegal value)
        # 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40    Error correction level
        (
            -1,
            7,
            10,
            15,
            20,
            26,
            18,
            20,
            24,
            30,
            18,
            20,
            24,
            26,
            30,
            22,
            24,
            28,
            30,
            28,
            28,
            28,
            28,
            30,
            30,
            26,
            28,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
        ),  # Low
        (
            -1,
            10,
            16,
            26,
            18,
            24,
            16,
            18,
            22,
            22,
            26,
            30,
            22,
            22,
            24,
            24,
            28,
            28,
            26,
            26,
            26,
            26,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
            28,
        ),  # Medium
        (
            -1,
            13,
            22,
            18,
            26,
            18,
            24,
            18,
            22,
            20,
            24,
            28,
            26,
            24,
            20,
            30,
            24,
            28,
            28,
            26,
            30,
            28,
            30,
            30,
            30,
            30,
            28,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
        ),  # Quartile
        (
            -1,
            17,
            28,
            22,
            16,
            22,
            28,
            26,
            26,
            24,
            28,
            24,
            28,
            22,
            24,
            24,
            30,
            28,
            28,
            26,
            28,
            30,
            24,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
            30,
        ),
    )  # High

    _NUM_ERROR_CORRECTION_BLOCKS: Sequence[Sequence[int]] = (
        # Version: (note that index 0 is for padding, and is set to an illegal value)
        # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40    Error correction level
        (
            -1,
            1,
            1,
            1,
            1,
            1,
            2,
            2,
            2,
            2,
            4,
            4,
            4,
            4,
            4,
            6,
            6,
            6,
            6,
            7,
            8,
            8,
            9,
            9,
            10,
            12,
            12,
            12,
            13,
            14,
            15,
            16,
            17,
            18,
            19,
            19,
            20,
            21,
            22,
            24,
            25,
        ),  # Low
        (
            -1,
            1,
            1,
            1,
            2,
            2,
            4,
            4,
            4,
            5,
            5,
            5,
            8,
            9,
            9,
            10,
            10,
            11,
            13,
            14,
            16,
            17,
            17,
            18,
            20,
            21,
            23,
            25,
            26,
            28,
            29,
            31,
            33,
            35,
            37,
            38,
            40,
            43,
            45,
            47,
            49,
        ),  # Medium
        (
            -1,
            1,
            1,
            2,
            2,
            4,
            4,
            6,
            6,
            8,
            8,
            8,
            10,
            12,
            16,
            12,
            17,
            16,
            18,
            21,
            20,
            23,
            23,
            25,
            27,
            29,
            34,
            34,
            35,
            38,
            40,
            43,
            45,
            48,
            51,
            53,
            56,
            59,
            62,
            65,
            68,
        ),  # Quartile
        (
            -1,
            1,
            1,
            2,
            4,
            4,
            4,
            5,
            6,
            8,
            8,
            11,
            11,
            16,
            16,
            18,
            16,
            19,
            21,
            25,
            25,
            25,
            34,
            30,
            32,
            35,
            37,
            40,
            42,
            45,
            48,
            51,
            54,
            57,
            60,
            63,
            66,
            70,
            74,
            77,
            81,
        ),
    )  # High

    _MASK_PATTERNS: Sequence[Callable[[int, int], int]] = (
        (lambda x, y: (x + y) % 2),
        (lambda x, y: y % 2),
        (lambda x, y: x % 3),
        (lambda x, y: (x + y) % 3),
        (lambda x, y: (x // 3 + y // 2) % 2),
        (lambda x, y: x * y % 2 + x * y % 3),
        (lambda x, y: (x * y % 2 + x * y % 3) % 2),
        (lambda x, y: ((x + y) % 2 + x * y % 3) % 2),
    )

    # ---- Public helper enumeration ----

    class Ecc:
        ordinal: int  # (Public) In the range 0 to 3 (unsigned 2-bit integer)
        formatbits: (
            int  # (Package-private) In the range 0 to 3 (unsigned 2-bit integer)
        )

        """The error correction level in a QR Code symbol. Immutable."""

        # Private constructor
        def __init__(self, i: int, fb: int) -> None:
            self.ordinal = i
            self.formatbits = fb

        # Placeholders
        LOW: QrCode.Ecc
        MEDIUM: QrCode.Ecc
        QUARTILE: QrCode.Ecc
        HIGH: QrCode.Ecc

    # Public constants. Create them outside the class.
    Ecc.LOW = Ecc(0, 1)  # The QR Code can tolerate about  7% erroneous codewords
    Ecc.MEDIUM = Ecc(1, 0)  # The QR Code can tolerate about 15% erroneous codewords
    Ecc.QUARTILE = Ecc(2, 3)  # The QR Code can tolerate about 25% erroneous codewords
    Ecc.HIGH = Ecc(3, 2)  # The QR Code can tolerate about 30% erroneous codewords

Ecc

Source code in qr/qr.py
class Ecc:
    ordinal: int  # (Public) In the range 0 to 3 (unsigned 2-bit integer)
    formatbits: (
        int  # (Package-private) In the range 0 to 3 (unsigned 2-bit integer)
    )

    """The error correction level in a QR Code symbol. Immutable."""

    # Private constructor
    def __init__(self, i: int, fb: int) -> None:
        self.ordinal = i
        self.formatbits = fb

    # Placeholders
    LOW: QrCode.Ecc
    MEDIUM: QrCode.Ecc
    QUARTILE: QrCode.Ecc
    HIGH: QrCode.Ecc
formatbits = fb instance-attribute

The error correction level in a QR Code symbol. Immutable.

encode_text(text, ecl) staticmethod

Returns a QR Code representing the given Unicode text string at the given error correction level. As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.

Source code in qr/qr.py
@staticmethod
def encode_text(text: str, ecl: QrCode.Ecc) -> QrCode:
    """Returns a QR Code representing the given Unicode text string at the given error correction level.
    As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
    Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
    QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
    ecl argument if it can be done without increasing the version."""
    segs: list[QrSegment] = QrSegment.make_segments(text)
    return QrCode.encode_segments(segs, ecl)

encode_binary(data, ecl) staticmethod

Returns a QR Code representing the given binary data at the given error correction level. This function always encodes using the binary segment mode, not any text mode. The maximum number of bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.

Source code in qr/qr.py
@staticmethod
def encode_binary(data: Union[bytes, Sequence[int]], ecl: QrCode.Ecc) -> QrCode:
    """Returns a QR Code representing the given binary data at the given error correction level.
    This function always encodes using the binary segment mode, not any text mode. The maximum number of
    bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
    The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version."""
    return QrCode.encode_segments([QrSegment.make_bytes(data)], ecl)

encode_segments(segs, ecl, minversion=1, maxversion=40, mask=-1, boostecl=True) staticmethod

Returns a QR Code representing the given segments with the given encoding parameters. The smallest possible QR Code version within the given range is automatically chosen for the output. Iff boostecl is true, then the ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. The mask number is either between 0 to 7 (inclusive) to force that mask, or -1 to automatically choose an appropriate mask (which may be slow). This function allows the user to create a custom sequence of segments that switches between modes (such as alphanumeric and byte) to encode text in less space. This is a mid-level API; the high-level API is encode_text() and encode_binary().

Source code in qr/qr.py
@staticmethod
def encode_segments(
    segs: Sequence[QrSegment],
    ecl: QrCode.Ecc,
    minversion: int = 1,
    maxversion: int = 40,
    mask: int = -1,
    boostecl: bool = True,
) -> QrCode:
    """Returns a QR Code representing the given segments with the given encoding parameters.
    The smallest possible QR Code version within the given range is automatically
    chosen for the output. Iff boostecl is true, then the ECC level of the result
    may be higher than the ecl argument if it can be done without increasing the
    version. The mask number is either between 0 to 7 (inclusive) to force that
    mask, or -1 to automatically choose an appropriate mask (which may be slow).
    This function allows the user to create a custom sequence of segments that switches
    between modes (such as alphanumeric and byte) to encode text in less space.
    This is a mid-level API; the high-level API is encode_text() and encode_binary()."""

    if not (
        QrCode.MIN_VERSION <= minversion <= maxversion <= QrCode.MAX_VERSION
    ) or not (-1 <= mask <= 7):
        raise ValueError("Invalid value")

    # Find the minimal version number to use
    for version in range(minversion, maxversion + 1):
        datacapacitybits: int = (
            QrCode._get_num_data_codewords(version, ecl) * 8
        )  # Number of data bits available
        datausedbits: int | None = QrSegment.get_total_bits(segs, version)
        if (datausedbits is not None) and (datausedbits <= datacapacitybits):
            break  # This version number is found to be suitable
        if (
            version >= maxversion
        ):  # All versions in the range could not fit the given data
            msg: str = "Segment too long"
            if datausedbits is not None:
                msg = f"Data length = {datausedbits} bits, Max capacity = {datacapacitybits} bits"
            raise DataTooLongError(msg)
    assert datausedbits is not None

    # Increase the error correction level while the data still fits in the current version number
    for newecl in (
        QrCode.Ecc.MEDIUM,
        QrCode.Ecc.QUARTILE,
        QrCode.Ecc.HIGH,
    ):  # From low to high
        if boostecl and (
            datausedbits <= QrCode._get_num_data_codewords(version, newecl) * 8
        ):
            ecl = newecl

    # Concatenate all segments to create the data bit string
    bb = _BitBuffer()
    for seg in segs:
        bb.append_bits(seg.get_mode().get_mode_bits(), 4)
        bb.append_bits(
            seg.get_num_chars(), seg.get_mode().num_char_count_bits(version)
        )
        bb.extend(seg._bitdata)
    assert len(bb) == datausedbits

    # Add terminator and pad up to a byte if applicable
    datacapacitybits = QrCode._get_num_data_codewords(version, ecl) * 8
    assert len(bb) <= datacapacitybits
    bb.append_bits(0, min(4, datacapacitybits - len(bb)))
    bb.append_bits(
        0, -len(bb) % 8
    )  # Note: Python's modulo on negative numbers behaves better than C family languages
    assert len(bb) % 8 == 0

    # Pad with alternating bytes until data capacity is reached
    for padbyte in itertools.cycle((0xEC, 0x11)):
        if len(bb) >= datacapacitybits:
            break
        bb.append_bits(padbyte, 8)

    # Pack bits into bytes in big endian
    datacodewords = bb.pack_to_bytes()

    # Create the QR Code object
    return QrCode(version, ecl, datacodewords, mask)

__init__(version, errcorlvl, datacodewords, msk)

Creates a new QR Code with the given version number, error correction level, data codeword bytes, and mask number. This is a low-level API that most users should not use directly. A mid-level API is the encode_segments() function.

Source code in qr/qr.py
def __init__(
    self,
    version: int,
    errcorlvl: QrCode.Ecc,
    datacodewords: Union[bytes, Sequence[int]],
    msk: int,
) -> None:
    """Creates a new QR Code with the given version number,
    error correction level, data codeword bytes, and mask number.
    This is a low-level API that most users should not use directly.
    A mid-level API is the encode_segments() function."""

    # Check scalar arguments and set fields
    if not (QrCode.MIN_VERSION <= version <= QrCode.MAX_VERSION):
        raise ValueError("Version value out of range")
    if not (-1 <= msk <= 7):
        raise ValueError("Mask value out of range")

    self._version = version
    self._size = version * 4 + 17
    self._errcorlvl = errcorlvl

    # Initialize both grids to be size*size arrays of 0 (light)
    self._modules = [
        bytearray(self._size) for _ in range(self._size)
    ]  # Initially all light
    self._isfunction = [bytearray(self._size) for _ in range(self._size)]

    # Compute ECC, draw modules
    self._draw_function_patterns()
    allcodewords: bytes = self._add_ecc_and_interleave(bytearray(datacodewords))
    self._draw_codewords(allcodewords)

    # Do masking
    if msk == -1:  # Automatically choose best mask
        # Precompute mask grids to avoid per-pixel arithmetic and
        # isfunction checks during the 8-mask evaluation loop
        mask_grids = _build_mask_grids(self._isfunction, self._size)
        minpenalty: int = 1 << 32
        for i in range(8):
            _apply_precomputed_mask(self._modules, mask_grids[i], self._size)
            self._draw_format_bits(i)
            penalty = self._get_penalty_score()
            if penalty < minpenalty:
                msk = i
                minpenalty = penalty
            _apply_precomputed_mask(
                self._modules, mask_grids[i], self._size
            )  # Undoes the mask due to XOR
        assert 0 <= msk <= 7
        self._mask = msk
        _apply_precomputed_mask(self._modules, mask_grids[msk], self._size)
    else:
        self._mask = msk
        self._apply_mask(msk)  # Apply the specified mask
    self._draw_format_bits(msk)  # Overwrite old format bits

    del self._isfunction

get_version()

Returns this QR Code's version number, in the range [1, 40].

Source code in qr/qr.py
def get_version(self) -> int:
    """Returns this QR Code's version number, in the range [1, 40]."""
    return self._version

get_size()

Returns this QR Code's size, in the range [21, 177].

Source code in qr/qr.py
def get_size(self) -> int:
    """Returns this QR Code's size, in the range [21, 177]."""
    return self._size

get_error_correction_level()

Returns this QR Code's error correction level.

Source code in qr/qr.py
def get_error_correction_level(self) -> QrCode.Ecc:
    """Returns this QR Code's error correction level."""
    return self._errcorlvl

get_mask()

Returns this QR Code's mask, in the range [0, 7].

Source code in qr/qr.py
def get_mask(self) -> int:
    """Returns this QR Code's mask, in the range [0, 7]."""
    return self._mask

get_module(x, y)

Returns the color of the module (pixel) at the given coordinates, which is False for light or True for dark. The top left corner has the coordinates (x=0, y=0). If the given coordinates are out of bounds, then False (light) is returned.

Source code in qr/qr.py
def get_module(self, x: int, y: int) -> bool:
    """Returns the color of the module (pixel) at the given coordinates, which is False
    for light or True for dark. The top left corner has the coordinates (x=0, y=0).
    If the given coordinates are out of bounds, then False (light) is returned."""
    return (
        (0 <= x < self._size) and (0 <= y < self._size) and self._modules[y][x] != 0
    )

QrSegment

A segment of character/binary/control data in a QR Code symbol. Instances of this class are immutable. The mid-level way to create a segment is to take the payload data and call a static factory function such as QrSegment.make_numeric(). The low-level way to create a segment is to custom-make the bit buffer and call the QrSegment() constructor with appropriate values. This segment class imposes no length restrictions, but QR Codes have restrictions. Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. Any segment longer than this is meaningless for the purpose of generating QR Codes.

Source code in qr/qr.py
class QrSegment:
    """A segment of character/binary/control data in a QR Code symbol.
    Instances of this class are immutable.
    The mid-level way to create a segment is to take the payload data
    and call a static factory function such as QrSegment.make_numeric().
    The low-level way to create a segment is to custom-make the bit buffer
    and call the QrSegment() constructor with appropriate values.
    This segment class imposes no length restrictions, but QR Codes have restrictions.
    Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
    Any segment longer than this is meaningless for the purpose of generating QR Codes."""

    # ---- Static factory functions (mid level) ----

    @staticmethod
    def make_bytes(data: Union[bytes, Sequence[int]]) -> QrSegment:
        """Returns a segment representing the given binary data encoded in byte mode.
        All input byte lists are acceptable. Any text string can be converted to
        UTF-8 bytes (s.encode("UTF-8")) and encoded as a byte mode segment."""
        bb = _BitBuffer()
        for b in data:
            bb.append_bits(b, 8)
        return QrSegment(QrSegment.Mode.BYTE, len(data), bb)

    @staticmethod
    def make_numeric(digits: str) -> QrSegment:
        """Returns a segment representing the given string of decimal digits encoded in numeric mode."""
        if not QrSegment.is_numeric(digits):
            raise ValueError("String contains non-numeric characters")
        bb = _BitBuffer()
        i: int = 0
        while i < len(digits):  # Consume up to 3 digits per iteration
            n: int = min(len(digits) - i, 3)
            bb.append_bits(int(digits[i : i + n]), n * 3 + 1)
            i += n
        return QrSegment(QrSegment.Mode.NUMERIC, len(digits), bb)

    @staticmethod
    def make_alphanumeric(text: str) -> QrSegment:
        """Returns a segment representing the given text string encoded in alphanumeric mode.
        The characters allowed are: 0 to 9, A to Z (uppercase only), space,
        dollar, percent, asterisk, plus, hyphen, period, slash, colon."""
        if not QrSegment.is_alphanumeric(text):
            raise ValueError(
                "String contains unencodable characters in alphanumeric mode"
            )
        bb = _BitBuffer()
        for i in range(0, len(text) - 1, 2):  # Process groups of 2
            temp: int = QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[i]] * 45
            temp += QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[i + 1]]
            bb.append_bits(temp, 11)
        if len(text) % 2 > 0:  # 1 character remaining
            bb.append_bits(QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[-1]], 6)
        return QrSegment(QrSegment.Mode.ALPHANUMERIC, len(text), bb)

    @staticmethod
    def make_segments(text: str) -> list[QrSegment]:
        """Returns a new mutable list of zero or more segments to represent the given Unicode text string.
        The result may use various segment modes and switch modes to optimize the length of the bit stream."""

        # Select the most efficient segment encoding automatically
        if text == "":
            return []
        elif QrSegment.is_numeric(text):
            return [QrSegment.make_numeric(text)]
        elif QrSegment.is_alphanumeric(text):
            return [QrSegment.make_alphanumeric(text)]
        else:
            return [QrSegment.make_bytes(text.encode("UTF-8"))]

    @staticmethod
    def make_eci(assignval: int) -> QrSegment:
        """Returns a segment representing an Extended Channel Interpretation
        (ECI) designator with the given assignment value."""
        bb = _BitBuffer()
        if assignval < 0:
            raise ValueError("ECI assignment value out of range")
        elif assignval < (1 << 7):
            bb.append_bits(assignval, 8)
        elif assignval < (1 << 14):
            bb.append_bits(0b10, 2)
            bb.append_bits(assignval, 14)
        elif assignval < 1000000:
            bb.append_bits(0b110, 3)
            bb.append_bits(assignval, 21)
        else:
            raise ValueError("ECI assignment value out of range")
        return QrSegment(QrSegment.Mode.ECI, 0, bb)

    # Tests whether the given string can be encoded as a segment in numeric mode.
    # A string is encodable iff each character is in the range 0 to 9.
    @staticmethod
    def is_numeric(text: str) -> bool:
        return QrSegment._NUMERIC_REGEX.fullmatch(text) is not None

    # Tests whether the given string can be encoded as a segment in alphanumeric mode.
    # A string is encodable iff each character is in the following set: 0 to 9, A to Z
    # (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
    @staticmethod
    def is_alphanumeric(text: str) -> bool:
        return QrSegment._ALPHANUMERIC_REGEX.fullmatch(text) is not None

    # ---- Private fields ----

    # The mode indicator of this segment. Accessed through get_mode().
    _mode: QrSegment.Mode

    # The length of this segment's unencoded data. Measured in characters for
    # numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
    # Always zero or positive. Not the same as the data's bit length.
    # Accessed through get_num_chars().
    _numchars: int

    # The data bits of this segment. Accessed through get_data().
    _bitdata: _BitBuffer

    # ---- Constructor (low level) ----

    def __init__(
        self,
        mode: QrSegment.Mode,
        numch: int,
        bitdata: Union[_BitBuffer, Sequence[int]],
    ) -> None:
        """Creates a new QR Code segment with the given attributes and data.
        The character count (numch) must agree with the mode and the bit buffer length,
        but the constraint isn't checked. The given bit buffer is cloned and stored."""
        if numch < 0:
            raise ValueError()
        self._mode = mode
        self._numchars = numch
        if isinstance(bitdata, _BitBuffer):
            self._bitdata = _BitBuffer(bitdata._data, bitdata._length)
        else:
            bb = _BitBuffer()
            for bit in bitdata:
                bb._data = (bb._data << 1) | bit
                bb._length += 1
            self._bitdata = bb

    # ---- Accessor methods ----

    def get_mode(self) -> QrSegment.Mode:
        """Returns the mode field of this segment."""
        return self._mode

    def get_num_chars(self) -> int:
        """Returns the character count field of this segment."""
        return self._numchars

    def get_data(self) -> list[int]:
        """Returns a new copy of the data bits of this segment."""
        return list(self._bitdata)  # Make defensive copy

    # Package-private function
    @staticmethod
    def get_total_bits(segs: Sequence[QrSegment], version: int) -> int | None:
        """Calculates the number of bits needed to encode the given segments at
        the given version. Returns a non-negative number if successful. Otherwise
        returns None if a segment has too many characters to fit its length field."""
        result = 0
        for seg in segs:
            ccbits: int = seg.get_mode().num_char_count_bits(version)
            if seg.get_num_chars() >= (1 << ccbits):
                return None  # The segment's length doesn't fit the field's bit width
            result += 4 + ccbits + len(seg._bitdata)
        return result

    # ---- Constants ----

    # Describes precisely all strings that are encodable in numeric mode.
    _NUMERIC_REGEX: re.Pattern[str] = re.compile(r"[0-9]*")

    # Describes precisely all strings that are encodable in alphanumeric mode.
    _ALPHANUMERIC_REGEX: re.Pattern[str] = re.compile(r"[A-Z0-9 $%*+./:-]*")

    # Dictionary of "0"->0, "A"->10, "$"->37, etc.
    _ALPHANUMERIC_ENCODING_TABLE: dict[str, int] = {
        ch: i for (i, ch) in enumerate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:")
    }

    # ---- Public helper enumeration ----

    class Mode:
        """Describes how a segment's data bits are interpreted. Immutable."""

        _modebits: (
            int  # The mode indicator bits, which is a uint4 value (range 0 to 15)
        )
        _charcounts: tuple[
            int, int, int
        ]  # Number of character count bits for three different version ranges

        # Private constructor
        def __init__(self, modebits: int, charcounts: tuple[int, int, int]):
            self._modebits = modebits
            self._charcounts = charcounts

        # Package-private method
        def get_mode_bits(self) -> int:
            """Returns an unsigned 4-bit integer value (range 0 to 15) representing the mode indicator bits for this mode object."""
            return self._modebits

        # Package-private method
        def num_char_count_bits(self, ver: int) -> int:
            """Returns the bit width of the character count field for a segment in this mode
            in a QR Code at the given version number. The result is in the range [0, 16]."""
            return self._charcounts[(ver + 7) // 17]

        # Placeholders
        NUMERIC: QrSegment.Mode
        ALPHANUMERIC: QrSegment.Mode
        BYTE: QrSegment.Mode
        KANJI: QrSegment.Mode
        ECI: QrSegment.Mode

    # Public constants. Create them outside the class.
    Mode.NUMERIC = Mode(0x1, (10, 12, 14))
    Mode.ALPHANUMERIC = Mode(0x2, (9, 11, 13))
    Mode.BYTE = Mode(0x4, (8, 16, 16))
    Mode.KANJI = Mode(0x8, (8, 10, 12))
    Mode.ECI = Mode(0x7, (0, 0, 0))

Mode

Describes how a segment's data bits are interpreted. Immutable.

Source code in qr/qr.py
class Mode:
    """Describes how a segment's data bits are interpreted. Immutable."""

    _modebits: (
        int  # The mode indicator bits, which is a uint4 value (range 0 to 15)
    )
    _charcounts: tuple[
        int, int, int
    ]  # Number of character count bits for three different version ranges

    # Private constructor
    def __init__(self, modebits: int, charcounts: tuple[int, int, int]):
        self._modebits = modebits
        self._charcounts = charcounts

    # Package-private method
    def get_mode_bits(self) -> int:
        """Returns an unsigned 4-bit integer value (range 0 to 15) representing the mode indicator bits for this mode object."""
        return self._modebits

    # Package-private method
    def num_char_count_bits(self, ver: int) -> int:
        """Returns the bit width of the character count field for a segment in this mode
        in a QR Code at the given version number. The result is in the range [0, 16]."""
        return self._charcounts[(ver + 7) // 17]

    # Placeholders
    NUMERIC: QrSegment.Mode
    ALPHANUMERIC: QrSegment.Mode
    BYTE: QrSegment.Mode
    KANJI: QrSegment.Mode
    ECI: QrSegment.Mode
get_mode_bits()

Returns an unsigned 4-bit integer value (range 0 to 15) representing the mode indicator bits for this mode object.

Source code in qr/qr.py
def get_mode_bits(self) -> int:
    """Returns an unsigned 4-bit integer value (range 0 to 15) representing the mode indicator bits for this mode object."""
    return self._modebits
num_char_count_bits(ver)

Returns the bit width of the character count field for a segment in this mode in a QR Code at the given version number. The result is in the range [0, 16].

Source code in qr/qr.py
def num_char_count_bits(self, ver: int) -> int:
    """Returns the bit width of the character count field for a segment in this mode
    in a QR Code at the given version number. The result is in the range [0, 16]."""
    return self._charcounts[(ver + 7) // 17]

make_bytes(data) staticmethod

Returns a segment representing the given binary data encoded in byte mode. All input byte lists are acceptable. Any text string can be converted to UTF-8 bytes (s.encode("UTF-8")) and encoded as a byte mode segment.

Source code in qr/qr.py
@staticmethod
def make_bytes(data: Union[bytes, Sequence[int]]) -> QrSegment:
    """Returns a segment representing the given binary data encoded in byte mode.
    All input byte lists are acceptable. Any text string can be converted to
    UTF-8 bytes (s.encode("UTF-8")) and encoded as a byte mode segment."""
    bb = _BitBuffer()
    for b in data:
        bb.append_bits(b, 8)
    return QrSegment(QrSegment.Mode.BYTE, len(data), bb)

make_numeric(digits) staticmethod

Returns a segment representing the given string of decimal digits encoded in numeric mode.

Source code in qr/qr.py
@staticmethod
def make_numeric(digits: str) -> QrSegment:
    """Returns a segment representing the given string of decimal digits encoded in numeric mode."""
    if not QrSegment.is_numeric(digits):
        raise ValueError("String contains non-numeric characters")
    bb = _BitBuffer()
    i: int = 0
    while i < len(digits):  # Consume up to 3 digits per iteration
        n: int = min(len(digits) - i, 3)
        bb.append_bits(int(digits[i : i + n]), n * 3 + 1)
        i += n
    return QrSegment(QrSegment.Mode.NUMERIC, len(digits), bb)

make_alphanumeric(text) staticmethod

Returns a segment representing the given text string encoded in alphanumeric mode. The characters allowed are: 0 to 9, A to Z (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.

Source code in qr/qr.py
@staticmethod
def make_alphanumeric(text: str) -> QrSegment:
    """Returns a segment representing the given text string encoded in alphanumeric mode.
    The characters allowed are: 0 to 9, A to Z (uppercase only), space,
    dollar, percent, asterisk, plus, hyphen, period, slash, colon."""
    if not QrSegment.is_alphanumeric(text):
        raise ValueError(
            "String contains unencodable characters in alphanumeric mode"
        )
    bb = _BitBuffer()
    for i in range(0, len(text) - 1, 2):  # Process groups of 2
        temp: int = QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[i]] * 45
        temp += QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[i + 1]]
        bb.append_bits(temp, 11)
    if len(text) % 2 > 0:  # 1 character remaining
        bb.append_bits(QrSegment._ALPHANUMERIC_ENCODING_TABLE[text[-1]], 6)
    return QrSegment(QrSegment.Mode.ALPHANUMERIC, len(text), bb)

make_segments(text) staticmethod

Returns a new mutable list of zero or more segments to represent the given Unicode text string. The result may use various segment modes and switch modes to optimize the length of the bit stream.

Source code in qr/qr.py
@staticmethod
def make_segments(text: str) -> list[QrSegment]:
    """Returns a new mutable list of zero or more segments to represent the given Unicode text string.
    The result may use various segment modes and switch modes to optimize the length of the bit stream."""

    # Select the most efficient segment encoding automatically
    if text == "":
        return []
    elif QrSegment.is_numeric(text):
        return [QrSegment.make_numeric(text)]
    elif QrSegment.is_alphanumeric(text):
        return [QrSegment.make_alphanumeric(text)]
    else:
        return [QrSegment.make_bytes(text.encode("UTF-8"))]

make_eci(assignval) staticmethod

Returns a segment representing an Extended Channel Interpretation (ECI) designator with the given assignment value.

Source code in qr/qr.py
@staticmethod
def make_eci(assignval: int) -> QrSegment:
    """Returns a segment representing an Extended Channel Interpretation
    (ECI) designator with the given assignment value."""
    bb = _BitBuffer()
    if assignval < 0:
        raise ValueError("ECI assignment value out of range")
    elif assignval < (1 << 7):
        bb.append_bits(assignval, 8)
    elif assignval < (1 << 14):
        bb.append_bits(0b10, 2)
        bb.append_bits(assignval, 14)
    elif assignval < 1000000:
        bb.append_bits(0b110, 3)
        bb.append_bits(assignval, 21)
    else:
        raise ValueError("ECI assignment value out of range")
    return QrSegment(QrSegment.Mode.ECI, 0, bb)

__init__(mode, numch, bitdata)

Creates a new QR Code segment with the given attributes and data. The character count (numch) must agree with the mode and the bit buffer length, but the constraint isn't checked. The given bit buffer is cloned and stored.

Source code in qr/qr.py
def __init__(
    self,
    mode: QrSegment.Mode,
    numch: int,
    bitdata: Union[_BitBuffer, Sequence[int]],
) -> None:
    """Creates a new QR Code segment with the given attributes and data.
    The character count (numch) must agree with the mode and the bit buffer length,
    but the constraint isn't checked. The given bit buffer is cloned and stored."""
    if numch < 0:
        raise ValueError()
    self._mode = mode
    self._numchars = numch
    if isinstance(bitdata, _BitBuffer):
        self._bitdata = _BitBuffer(bitdata._data, bitdata._length)
    else:
        bb = _BitBuffer()
        for bit in bitdata:
            bb._data = (bb._data << 1) | bit
            bb._length += 1
        self._bitdata = bb

get_mode()

Returns the mode field of this segment.

Source code in qr/qr.py
def get_mode(self) -> QrSegment.Mode:
    """Returns the mode field of this segment."""
    return self._mode

get_num_chars()

Returns the character count field of this segment.

Source code in qr/qr.py
def get_num_chars(self) -> int:
    """Returns the character count field of this segment."""
    return self._numchars

get_data()

Returns a new copy of the data bits of this segment.

Source code in qr/qr.py
def get_data(self) -> list[int]:
    """Returns a new copy of the data bits of this segment."""
    return list(self._bitdata)  # Make defensive copy

get_total_bits(segs, version) staticmethod

Calculates the number of bits needed to encode the given segments at the given version. Returns a non-negative number if successful. Otherwise returns None if a segment has too many characters to fit its length field.

Source code in qr/qr.py
@staticmethod
def get_total_bits(segs: Sequence[QrSegment], version: int) -> int | None:
    """Calculates the number of bits needed to encode the given segments at
    the given version. Returns a non-negative number if successful. Otherwise
    returns None if a segment has too many characters to fit its length field."""
    result = 0
    for seg in segs:
        ccbits: int = seg.get_mode().num_char_count_bits(version)
        if seg.get_num_chars() >= (1 << ccbits):
            return None  # The segment's length doesn't fit the field's bit width
        result += 4 + ccbits + len(seg._bitdata)
    return result

DataTooLongError

Bases: ValueError

Raised when the supplied data does not fit any QR Code version. Ways to handle this exception include: - Decrease the error correction level if it was greater than Ecc.LOW. - If the encode_segments() function was called with a maxversion argument, then increase it if it was less than QrCode.MAX_VERSION. (This advice does not apply to the other factory functions because they search all versions up to QrCode.MAX_VERSION.) - Split the text data into better or optimal segments in order to reduce the number of bits required. - Change the text or binary data to be shorter. - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric). - Propagate the error upward to the caller/user.

Source code in qr/qr.py
class DataTooLongError(ValueError):
    """Raised when the supplied data does not fit any QR Code version. Ways to handle this exception include:
    - Decrease the error correction level if it was greater than Ecc.LOW.
    - If the encode_segments() function was called with a maxversion argument, then increase
      it if it was less than QrCode.MAX_VERSION. (This advice does not apply to the other
      factory functions because they search all versions up to QrCode.MAX_VERSION.)
    - Split the text data into better or optimal segments in order to reduce the number of bits required.
    - Change the text or binary data to be shorter.
    - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric).
    - Propagate the error upward to the caller/user."""

    pass

print_qr_terminal(text)

Encode text as QR code and print to terminal using Unicode block characters.

Uses half-block characters to render two rows per line for compact output.

Source code in qr/qr.py
def print_qr_terminal(text: str) -> None:
    """Encode text as QR code and print to terminal using Unicode block characters.

    Uses half-block characters to render two rows per line for compact output.
    """
    qr = QrCode.encode_text(text, QrCode.Ecc.LOW)
    size = qr.get_size()
    border = 1

    # Use upper-half-block: "▀", lower-half-block: "▄", full block: "█", space: " "
    BOTH_DARK = "█"
    TOP_DARK = "▀"
    BOT_DARK = "▄"
    BOTH_LIGHT = " "

    lines: list[str] = []
    # Process two rows at a time
    for y in range(-border, size + border, 2):
        row_chars: list[str] = []
        for x in range(-border, size + border):
            top = qr.get_module(x, y)
            bot = qr.get_module(x, y + 1) if (y + 1) < (size + border) else False
            if top and bot:
                row_chars.append(BOTH_DARK)
            elif top:
                row_chars.append(TOP_DARK)
            elif bot:
                row_chars.append(BOT_DARK)
            else:
                row_chars.append(BOTH_LIGHT)
        lines.append("".join(row_chars))

    print("\n".join(lines))

qr_to_svg(qr, dest=None, *, scale=10, border=4, fg_color='#000000', bg_color='#ffffff')

Render a QR Code as an SVG image.

Parameters:

Name Type Description Default
qr QrCode

QR Code to render.

required
dest str | PathLike[str] | None

File path to write SVG to, or None to return the SVG string.

None
scale int

Size of each QR module in SVG user units.

10
border int

Width of the quiet zone in QR modules.

4
fg_color str

CSS color for dark modules.

'#000000'
bg_color str

CSS color for light modules.

'#ffffff'

Returns:

Type Description
str | None

SVG string when dest is None, otherwise None.

Source code in qr/qr.py
def qr_to_svg(
    qr: QrCode,
    dest: str | os.PathLike[str] | None = None,
    *,
    scale: int = 10,
    border: int = 4,
    fg_color: str = "#000000",
    bg_color: str = "#ffffff",
) -> str | None:
    """Render a QR Code as an SVG image.

    Args:
        qr: QR Code to render.
        dest: File path to write SVG to, or ``None`` to return the SVG string.
        scale: Size of each QR module in SVG user units.
        border: Width of the quiet zone in QR modules.
        fg_color: CSS color for dark modules.
        bg_color: CSS color for light modules.

    Returns:
        SVG string when *dest* is ``None``, otherwise ``None``.
    """
    size = qr.get_size()
    total = (size + 2 * border) * scale

    # Build a single <path> collecting all dark modules.
    parts: list[str] = []
    for y in range(size):
        for x in range(size):
            if qr.get_module(x, y):
                px = (x + border) * scale
                py = (y + border) * scale
                parts.append(f"M{px},{py}h{scale}v{scale}h-{scale}z")
    path_d = "".join(parts)

    svg = (
        f'<svg xmlns="http://www.w3.org/2000/svg" '
        f'viewBox="0 0 {total} {total}" '
        f'width="{total}" height="{total}">\n'
        f'<rect width="100%" height="100%" fill="{bg_color}"/>\n'
        f'<path d="{path_d}" fill="{fg_color}"/>\n'
        f"</svg>\n"
    )

    if dest is None:
        return svg
    with open(dest, "w", encoding="utf-8") as fh:
        fh.write(svg)
    return None

qr_to_png(qr, dest=None, *, scale=10, border=4, fg_color=0, bg_color=255)

Render a QR Code as a PNG image.

Requires the sibling png module.

Parameters:

Name Type Description Default
qr QrCode

QR Code to render.

required
dest str | PathLike[str] | None

File path to write PNG to, or None to return PNG bytes.

None
scale int

Pixels per QR module.

10
border int

Width of the quiet zone in QR modules.

4
fg_color int

Grayscale value (0--255) for dark modules.

0
bg_color int

Grayscale value (0--255) for light modules.

255

Returns:

Type Description
bytes | None

PNG bytes when dest is None, otherwise None.

Raises:

Type Description
ImportError

If the sibling png module is not available.

ValueError

If fg_color or bg_color is outside 0--255.

Source code in qr/qr.py
def qr_to_png(
    qr: QrCode,
    dest: str | os.PathLike[str] | None = None,
    *,
    scale: int = 10,
    border: int = 4,
    fg_color: int = 0,
    bg_color: int = 255,
) -> bytes | None:
    """Render a QR Code as a PNG image.

    Requires the sibling ``png`` module.

    Args:
        qr: QR Code to render.
        dest: File path to write PNG to, or ``None`` to return PNG bytes.
        scale: Pixels per QR module.
        border: Width of the quiet zone in QR modules.
        fg_color: Grayscale value (0--255) for dark modules.
        bg_color: Grayscale value (0--255) for light modules.

    Returns:
        PNG bytes when *dest* is ``None``, otherwise ``None``.

    Raises:
        ImportError: If the sibling ``png`` module is not available.
        ValueError: If *fg_color* or *bg_color* is outside 0--255.
    """
    if not (0 <= fg_color <= 255):
        raise ValueError(f"fg_color must be 0-255, got {fg_color}")
    if not (0 <= bg_color <= 255):
        raise ValueError(f"bg_color must be 0-255, got {bg_color}")

    Image, encode_png = _load_png_encoder()

    size = qr.get_size()
    total_px = (size + 2 * border) * scale

    # Build grayscale pixel buffer.
    fg_run = bytes([fg_color]) * scale
    pixels = bytearray([bg_color]) * (total_px * total_px)
    for y in range(size):
        for x in range(size):
            if qr.get_module(x, y):
                px = (x + border) * scale
                py = (y + border) * scale
                for row in range(py, py + scale):
                    offset = row * total_px + px
                    pixels[offset : offset + scale] = fg_run

    img = Image(width=total_px, height=total_px, data=bytes(pixels), mode="L")
    return encode_png(img, dest)