Удаление элементов кортежа
Удалить отдельный элемент из кортежа нельзя:
>>> del tup3 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object doesn't support item deletion
Но — ничего не мешает создать новый, без ненужного элемента:
>>> tup1 = (1, 2, 3) >>> del tup1 >>> tup2 = tup1 >>> print tup2 (1, 2)
Что бы удалить кортеж полностью — используется тот же оператор del:
>>> tup = ('physics', 'chemistry', 1997, 2000); >>> >>> print tup; ('physics', 'chemistry', 1997, 2000) >>> del tup; >>> print "After deleting tup : " After deleting tup : >>> print tup; Traceback (most recent call last): File "", line 1, in NameE
Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed.
We can also assign a tuple to different values (reassignment).
my_tuple = (4, 2, 3, ) # TypeError: 'tuple' object does not support item assignment # my_tuple = 9 # However, item of mutable element can be changed my_tuple = 9 # Output: (4, 2, 3, ) print(my_tuple) # Tuples can be reassigned my_tuple = ('p','r','o','g','r','a','m','i','z') # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple)
We can use operator to combine two tuples. This is also called concatenation.
We can also repeat the elements in a tuple for a given number of times using the operator.
Both and operations result in a new tuple.
# Concatenation # Output: (1, 2, 3, 4, 5, 6) print((1, 2, 3) + (4, 5, 6)) # Repeat # Output: ('Repeat', 'Repeat', 'Repeat') print(("Repeat",) * 3)
Не уступает дата-классам
Раз уж мы заговорили о генерации кода. В питоне 3.7 появился убер-генератор кода, которому нет равных — дата-классы (dataclasses).
Когда впервые видишь дата-класс, хочется перейти на новую версию языка только ради него:
Чудо как хорош! Но есть нюанс — он толстый:
Дата-класс генерит обычный питонячий класс, объекты которого изнемогают под тяжестью . Так что если вы начитываете из базы вагон строк и превращаете их в объекты, дата-классы — не лучший выбор.
Но постойте, дата-класс ведь можно «заморозить», как кортеж. Может тогда он станет легче?
Увы. Даже замороженный, он остался обычным увесистым объектом со словарём атрибутов. Так что если вам нужны лёгкие неизменяемые объекты (которые к тому же можно использовать как обычные кортежи) — namedtuple по-прежнему лучший выбор.
⌘ ⌘ ⌘
Мне очень нравится именованный кортеж:
- честный iterable,
- динамическое объявление типов,
- именованный доступ к атрибутам,
- лёгкий и неизменяемый.
И при этом реализован в 150 строк кода. Что ещё надо для счастья ツ
Если хотите узнать больше о стандартной библиотеке Python — подписывайтесь на канал @ohmypy
Списки
Списки Python схожи с массивами в других языках. В Python, пустой список может быть создан следующим образом:
Python
my_list = []
my_list = list()
1 |
my_list= my_list=list() |
Как вы видите, вы можете создать список при помощи квадратных скобок, или при помощи встроенного инструмента Python – list. Список состоит из таких элементов, как строки, цифры, объекты и смеси типов. Давайте взглянем на несколько примеров:
Python
my_list =
my_list2 =
my_list3 =
1 |
my_list=1,2,3 my_list2=»a»,»b»,»c» my_list3=»a»,1,»Python»,5 |
Первый список содержит 3 числа, второй 3 строки, третий содержит смесь. Вы также можете создавать списки списков, вот так:
Python
my_nested_list =
print(my_nested_list) # , ]
1 |
my_nested_list=my_list,my_list2 print(my_nested_list)# , ] |
В какой-то момент вам может понадобиться скомбинировать два списка вместе. Первый способ сделать это – при помощи метода extend:
Python
combo_list =
one_list =
a = combo_list.extend(one_list)
print(a) #
1 |
combo_list=1 one_list=4,5 a=combo_list.extend(one_list) print(a)# |
Немного проще будет просто добавить два списка вместе.
Python
my_list =
my_list2 =
combo_list = my_list + my_list2
print(combo_list) #
1 |
my_list=1,2,3 my_list2=»a»,»b»,»c» combo_list=my_list+my_list2 print(combo_list)# |
Да, это именно настолько просто. Вы также можете сортировать список. Давайте уделим немного времени и взглянем на то, как это делается:
Python
alpha_list =
alpha_list.sort()
print(alpha_list) #
1 |
alpha_list=34,23,67,100,88,2 alpha_list.sort() print(alpha_list)# |
Получилось. Видите? Давайте взглянем на еще один пример, чтобы закрепить результат:
Python
alpha_list =
sorted_list = alpha_list.sort()
print(sorted_list) # None
1 |
alpha_list=34,23,67,100,88,2 sorted_list=alpha_list.sort() print(sorted_list)# None |
В этом примере мы попытались назначить сортированный список переменной. Однако, когда вы вызываете метод sort() в списке, он сортирует список на месте. Так что если вы попробуете назначить результат другой переменной, тогда возникнет объект None, который аналогичен объекту Null в других языках. Таким образом, когда вам нужно отсортировать что-нибудь, просто помните, что вы сортируете на месте, и вы не можете назначить объект другой переменной.
Вы можете разрезать список также, как вы делаете это со строкой:
Python
a = alpha_list
print(a) #
1 |
a=alpha_list3 print(a)# |
Данный код выдает список из трех первых элементов.
Обзор изменений синтаксиса
Этот раздел дает краткий обзор каждого синтаксического изменения Python 3.0.
Новый синтаксис
PEP 3107: аннотации для аргументов функции и возвращаемых значений.
>>> def foo(a 'x', b 5 + 6, c list) -> max(2, 9): ... pass >>> foo.__annotations__ {'a': 'x', 'b': 11, 'c': , 'return': 9}
PEP 3102: Keyword-only аргументы.
PEP 3104: nonlocal. Переменная во внешней (но не глобальной) области видимости.
>>> def outer(): ... x = 1 ... def inner(): ... x = 2 ... print("inner:", x) ... inner() ... print("outer:", x) ... >>> outer() inner: 2 outer: 1 >>> def outer(): ... x = 1 ... def inner(): ... nonlocal x ... x = 2 ... print("inner:", x) ... inner() ... print("outer:", x) ... >>> outer() inner: 2 outer: 2
PEP 3132: Extended Iterable Unpacking
>>> (a, *rest, b) = range(5) >>> a >>> rest >>> b 4
Генераторы словарей: {k: v for k, v in stuff} (то же самое, что и dict(stuff))
Литералы множеств (например, {1, 2}). Заметьте, что {} — это пустой словарь. Используйте set() для пустых множеств. Генераторы множеств: {x for x in stuff}
Новые восьмеричные литералы, например 0o720, вместо старых (0720).
Новые двоичные литералы, например 0b1010. Новая встроенная функция, bin().
Изменённый синтаксис
PEP 3109 and PEP 3134: новый синтаксис выражения raise: raise ].
«as» и «with» зарезервированные слова.
«True» и «False» и «None» — зарезервированные слова.
Изменено «except exc, var» на «except exc as var».
PEP 3115: Новый синтаксис для метаклассов. Вместо:
class C __metaclass__ = M ...
Вы должны использовать:
class C(metaclass=M): ...
Переменная __metaclass__ более не поддерживается.
Генераторы списков больше не поддерживают синтаксическую форму . Используйте .
4.8. Intermezzo: Coding Style¶
Now that you are about to write longer, more complex pieces of Python, it is a
good time to talk about coding style. Most languages can be written (or more
concise, formatted) in different styles; some are more readable than others.
Making it easy for others to read your code is always a good idea, and adopting
a nice coding style helps tremendously for that.
For Python, PEP 8 has emerged as the style guide that most projects adhere to;
it promotes a very readable and eye-pleasing coding style. Every Python
developer should read it at some point; here are the most important points
extracted for you:
-
Use 4-space indentation, and no tabs.
4 spaces are a good compromise between small indentation (allows greater
nesting depth) and large indentation (easier to read). Tabs introduce
confusion, and are best left out. -
Wrap lines so that they don’t exceed 79 characters.
This helps users with small displays and makes it possible to have several
code files side-by-side on larger displays. -
Use blank lines to separate functions and classes, and larger blocks of
code inside functions. -
When possible, put comments on a line of their own.
-
Use docstrings.
-
Use spaces around operators and after commas, but not directly inside
bracketing constructs: . -
Name your classes and functions consistently; the convention is to use
for classes and for functions
and methods. Always use as the name for the first method argument
(see for more on classes and methods). -
Don’t use fancy encodings if your code is meant to be used in international
environments. Python’s default, UTF-8, or even plain ASCII work best in any
case. -
Likewise, don’t use non-ASCII characters in identifiers if there is only the
slightest chance people speaking a different language will read or maintain
the code.
Footnotes
-
Actually, call by object reference would be a better description,
since if a mutable object is passed, the caller will see any changes the
callee makes to it (items inserted into a list).
Кортежи
Последнее обновление: 26.04.2017
Кортеж (tuple) представляет последовательность элементов, которая во многом похожа на список за тем исключением, что кортеж является неизменяемым
(immutable) типом. Поэтому мы не можем добавлять или удалять элементы в кортеже, изменять его.
Для создания кортежа используются круглые скобки, в которые помещаются его значения, разделенные запятыми:
user = ("Tom", 23) print(user)
Также для определения кортежа мы можем просто перечислить значения через запятую без применения скобок:
user = "Tom", 23 print(user)
Если вдруг кортеж состоит из одного элемента, то после единственного элемента кортежа необходимо поставить запятую:
user = ("Tom",)
Для создания кортежа из списка можно передать список в функцию tuple(), которая возвратит кортеж:
users_list = users_tuple = tuple(users_list) print(users_tuple) # ("Tom", "Bob", "Kate")
Обращение к элементам в кортеже происходит также, как и в списке по индексу. Индексация начинается также с нуля при получении элементов с начала списка и с -1 при получении элементов с конца списка:
users = ("Tom", "Bob", "Sam", "Kate") print(users) # Tom print(users) # Sam print(users) # Kate # получим часть кортежа со 2 элемента по 4 print(users) # ("Bob", "Sam", "Kate")
Но так как кортеж — неизменяемый тип (immutable), то мы не сможем изменить его элементы. То есть следующая запись работать не будет:
users = "Tim"
При необходимости мы можем разложить кортеж на отдельные переменные:
user = ("Tom", 22, False) name, age, isMarried = user print(name) # Tom print(age) # 22 print(isMarried) # False
Особенно удобно использовать кортежи, когда необходимо возвратить из функции сразу несколько значений. Когда функция возвращает несколько значений, фактически она возвращает в кортеж:
def get_user(): name = "Tom" age = 22 is_married = False return name, age, is_married user = get_user() print(user) # Tom print(user) # 22 print(user) # False
С помощью встроенной функции len() можно получить длину кортежа:
user = ("Tom", 22, False) print(len(user)) # 3
Перебор кортежей
Для перебора кортежа можно использовать стандартные циклы for и while. С помощью цикла for:
user = ("Tom", 22, False) for item in user: print(item)
С помощью цикла while:
user = ("Tom", 22, False) i = 0 while i
Как для списка с помощью выражения можно проверить наличие элемента в кортеже:
user = ("Tom", 22, False) name = "Tom" if name in user: print("Пользователя зовут Tom") else: print("Пользователь имеет другое имя")
Сложные кортежи
Один кортеж может содержать другие кортежи в виде элементов. Например:
countries = ( ("Germany", 80.2, (("Berlin",3.326), ("Hamburg", 1.718))), ("France", 66, (("Paris", 2.2),("Marsel", 1.6))) ) for country in countries: countryName, countryPopulation, cities = country print("\nCountry: {} population: {}".format(countryName, countryPopulation)) for city in cities: cityName, cityPopulation = city print("City: {} population: {}".format(cityName, cityPopulation))
Здесь кортеж countries, который представляет страны, состоит из кортежей, каждый из которых — отдельная страна.
Вложенные кортежи имеют три элемента: название страны, численность ее населения и города. Города представляют отдельный кортеж, где каждый отдельный город — это вложенный кортеж,
содержащий название города и численность его населения.
НазадВперед
Print — функция
Оператор print был заменён функцией print(), с именованными аргументами для замены большей части синтаксиса старого оператора print. Примеры:
Python2 print "The answer is", 2*2 Python3 print("The answer is", 2*2) Python2 print x, # Запятая в конце подавляет перевод строки Python3 print(x, end=" ") # Добавляет пробел вместо перевода строки Python2 print # Печатает перевод строки Python3 print() # Нужно вызвать функцию! Python2 print >>sys.stderr, "fatal error" Python3 print("fatal error", file=sys.stderr) Python2 print (x, y) # Печатает repr((x, y)) Python3 print((x, y)) # Не путать с print(x, y)!
Также вы можете настроить разделитель между элементами, например:
>>> print("There are , 2**32, "> possibilities!", sep="") There are possibilities!
Delete Tuple Elements
Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example −
#!/usr/bin/python tup = ('physics', 'chemistry', 1997, 2000); print tup; del tup; print "After deleting tup : "; print tup;
This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more −
('physics', 'chemistry', 1997, 2000) After deleting tup : Traceback (most recent call last): File "test.py", line 9, in print tup; NameError: name 'tup' is not defined
4.4. break and continue Statements, and else Clauses on Loops¶
The statement, like in C, breaks out of the innermost enclosing
or loop.
Loop statements may have an clause; it is executed when the loop
terminates through exhaustion of the iterable (with ) or when the
condition becomes false (with ), but not when the loop is
terminated by a statement. This is exemplified by the
following loop, which searches for prime numbers:
>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == ... print(n, 'equals', x, '*', n//x) ... break ... else ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3
(Yes, this is the correct code. Look closely: the clause belongs to
the loop, not the statement.)
When used with a loop, the clause has more in common with the
clause of a statement than it does with that of
statements: a statement’s clause runs
when no exception occurs, and a loop’s clause runs when no
occurs. For more on the statement and exceptions, see
.
The statement, also borrowed from C, continues with the next
iteration of the loop:
Adding more concise syntax
One objection to this PEP is that having to explicitly write Literal
feels verbose. For example, instead of writing:
def foobar(arg1: Literal, arg2: Literal) -> None: pass
…it would be nice to instead write:
def foobar(arg1: 1, arg2: True) -> None: pass
Unfortunately, these abbreviations simply will not work with the
existing implementation of typing at runtime. For example, the
following snippet crashes when run using Python 3.7:
from typing import Tuple # Supposed to accept tuple containing the literals 1 and 2 def foo(x: Tuple) -> None: pass
Running this yields the following exception:
TypeError: Tuple: each t must be a type. Got 1.
We don’t want users to have to memorize exactly when it’s ok to elide
Literal, so we require Literal to always be present.
A little more broadly, we feel overhauling the syntax of types in
Python is not within the scope of this PEP: it would be best to have
that discussion in a separate PEP, instead of attaching it to this one.
So, this PEP deliberately does not try and innovate Python’s type syntax.
Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
Sr.No. | Operator & Description |
---|---|
1 |
** Exponentiation (raise to the power) |
2 |
~ + — Complement, unary plus and minus (method names for the last two are +@ and -@) |
3 |
* / % // Multiply, divide, modulo and floor division |
4 |
+ — Addition and subtraction |
5 |
>> Right and left bitwise shift |
6 |
& Bitwise ‘AND’ |
7 |
^ | Bitwise exclusive `OR’ and regular `OR’ |
8 |
>= Comparison operators |
9 |
== != Equality operators |
10 |
= %= /= //= -= += *= **= Assignment operators |
11 |
is is not Identity operators |
12 |
in not in Membership operators |
13 |
not or and Logical operators |
Previous Page
Print Page
Next Page
UserList objects¶
This class acts as a wrapper around list objects. It is a useful base class
for your own list-like classes which can inherit from them and override
existing methods or add new ones. In this way, one can add new behaviors to
lists.
The need for this class has been partially supplanted by the ability to
subclass directly from ; however, this class can be easier
to work with because the underlying list is accessible as an attribute.
- class (list)
-
Class that simulates a list. The instance’s contents are kept in a regular
list, which is accessible via the attribute of
instances. The instance’s contents are initially set to a copy of list,
defaulting to the empty list . list can be any iterable, for
example a real Python list or a object.In addition to supporting the methods and operations of mutable sequences,
instances provide the following attribute:-
A real object used to store the contents of the
class.
-
Subclassing requirements: Subclasses of are expected to
offer a constructor which can be called with either no arguments or one
argument. List operations which return a new sequence attempt to create an
instance of the actual implementation class. To do so, it assumes that the
constructor can be called with a single parameter, which is a sequence object
used as a data source.
Interactions with generics
Types like Literal are meant to be just plain old subclasses of
int. This means you can use types like Literal anywhere
you could use normal types, such as with generics.
This means that it is legal to parameterize generic functions or
classes using Literal types:
A = TypeVar('A', bound=int) B = TypeVar('B', bound=int) C = TypeVar('C', bound=int) # A simplified definition for Matrix class Matrix(Generic): def __add__(self, other: Matrix) -> Matrix: ... def __matmul__(self, other: Matrix) -> Matrix: ... def transpose(self) -> Matrix: ... foo: Matrix, Literal] = Matrix(...) bar: Matrix, Literal] = Matrix(...) baz = foo @ bar reveal_type(baz) # Revealed type is 'Matrix, Literal]'
Similarly, it is legal to construct TypeVars with value restrictions
or bounds involving Literal types:
T = TypeVar('T', Literal, Literal, Literal) S = TypeVar('S', bound=Literal)
…although it is unclear when it would ever be useful to construct a
TypeVar with a Literal upper bound. For example, the S TypeVar in
the above example is essentially pointless: we can get equivalent behavior
by using S = Literal instead.
Note: Literal types and generics deliberately interact in only very
basic and limited ways. In particular, libraries that want to type check
code containing an heavy amount of numeric or numpy-style manipulation will
almost certainly likely find Literal types as proposed in this PEP to be
insufficient for their needs.
Текст, Unicode и 8-битные строки
Все, что вы знали о бинарных данных и Unicode, изменилось.
Python 3 использует понятия текста и (бинарных) данных вместо строк Unicode и 8-битных строк. Весь текст — Unicode; Однако кодированные Unicode строки представлены в виде двоичных данных. Тип , используемый для хранения текста является str, тип, используемый для хранения данных — bytes. Самое большое различие с python 2.x является то, что любая попытка комбинировать текст и данные в Python 3.0 поднимает TypeError, в то время как если бы вы смешивали Unicode и 8-битные строки в Python 2.x, это будет работать, если 8-битная строка содержала только 7-битные (ASCII) символы, но вы получите UnicodeDecodeError, если она содержит не-ASCII символы. Такое поведение вызывало многочисленные скорбные лица на протяжении многих лет.
Как следствие этого изменения в философии, значительная часть кода, который использует Unicode, кодировки или бинарные данные, скорее всего, должна измениться. Это изменения к лучшему, так как в python 2.x были многочисленные ошибки, имеющие отношение к смешиванию закодированного и декодированного текста. Чтобы быть подготовленным к этому, в Python 2.x следует начать использовать Unicode для всего незакодированного текста, и str только для бинарных или закодированных данных . Затем инструмент 2to3 будет делать большую часть работы за вас.
Вы можете больше не использовать литерал u»…» для текста Unicode. Тем не менее, вы должны использовать литерал b»…» для бинарных данных.
Так как str и bytes не могут быть смешаны, вы всегда должны их явно преобразовывать. Используйте str.encode(), чтобы перейти от str к bytes и bytes.decode(), чтобы перейти от bytes к str. Вы также можете использовать bytes(s, encoding=…) и str(b, encoding=…), соответственно.
Как str, тип bytes неизменен. Существует отдельный изменяемый тип для двоичных данных, bytearray. Почти все функции, которые принимают bytes также принимают bytearray.
Все обратные косые черты в «сырых» строковых литералах интерпретируются буквально. Это означает, что «\U» и «\u» в сырых строках не рассматриваются особо. Например, r»\u20ac» это строка из 6 символов в Python 3.0, в то время как в 2.6, ur»\u20ac» был один символ «евро». (Конечно, это изменение влияет только на сырые строковые литералы).
Встроенный абстрактный тип basestring был удален. Используйте str вместо него. str и bytes не имеют достаточно общей функциональности, чтобы оправдать общий базовый класс. Инструмент 2to3 (см. ниже) заменяет каждое вхождение basestring на str.
PEP 3138: repr() для строки больше не экранирует символы, не входящие в набор ASCII. Однако, он по-прежнему экранирует управляющие символы
PEP 3120: Кодировка исходного кода по умолчанию теперь UTF-8.
4.6. Defining Functions¶
We can create a function that writes the Fibonacci series to an arbitrary
boundary:
>>> def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" ... a, b = , 1 ... while a n ... print(a, end=' ') ... a, b = b, a+b ... print() ... >>> # Now call the function we just defined: ... fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
The keyword introduces a function definition. It must be
followed by the function name and the parenthesized list of formal parameters.
The statements that form the body of the function start at the next line, and
must be indented.
The first statement of the function body can optionally be a string literal;
this string literal is the function’s documentation string, or docstring.
(More about docstrings can be found in the section .)
There are tools which use docstrings to automatically produce online or printed
documentation, or to let the user interactively browse through code; it’s good
practice to include docstrings in code that you write, so make a habit of it.
The execution of a function introduces a new symbol table used for the local
variables of the function. More precisely, all variable assignments in a
function store the value in the local symbol table; whereas variable references
first look in the local symbol table, then in the local symbol tables of
enclosing functions, then in the global symbol table, and finally in the table
of built-in names. Thus, global variables and variables of enclosing functions
cannot be directly assigned a value within a function (unless, for global
variables, named in a statement, or, for variables of enclosing
functions, named in a statement), although they may be
referenced.
The actual parameters (arguments) to a function call are introduced in the local
symbol table of the called function when it is called; thus, arguments are
passed using call by value (where the value is always an object reference,
not the value of the object). When a function calls another function, a new
local symbol table is created for that call.
A function definition introduces the function name in the current symbol table.
The value of the function name has a type that is recognized by the interpreter
as a user-defined function. This value can be assigned to another name which
can then also be used as a function. This serves as a general renaming
mechanism:
>>> fib >>> f = fib >>> f(100) 0 1 1 2 3 5 8 13 21 34 55 89
Coming from other languages, you might object that is not a function but
a procedure since it doesn’t return a value. In fact, even functions without a
statement do return a value, albeit a rather boring one. This
value is called (it’s a built-in name). Writing the value is
normally suppressed by the interpreter if it would be the only value written.
You can see it if you really want to using :
>>> fib() >>> print(fib()) None
It is simple to write a function that returns a list of the numbers of the
Fibonacci series, instead of printing it:
>>> def fib2(n): # return Fibonacci series up to n ... """Return a list containing the Fibonacci series up to n.""" ... result = [] ... a, b = , 1 ... while a n ... result.append(a) # see below ... a, b = b, a+b ... return result ... >>> f100 = fib2(100) # call it >>> f100 # write the result
This example, as usual, demonstrates some new Python features:
Access Tuple Items
You can access tuple items by referring to the index number, inside square
brackets:
Example
Print the second item in the tuple:
thistuple = («apple», «banana», «cherry»)
print(thistuple)
Example
Print the last item of the tuple:
thistuple = («apple», «banana», «cherry»)
print(thistuple)
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
When specifying a range, the return value will be a new tuple with the
specified items.
Example
Return the third, fourth, and fifth item:
thistuple = («apple», «banana», «cherry», «orange», «kiwi», «melon», «mango»)
print(thistuple)
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = («apple», «banana», «cherry», «orange», «kiwi», «melon», «mango»)
print(thistuple)
Illegal parameters for Literal at type check time
The following parameters are intentionally disallowed by design:
- Arbitrary expressions like Literal or
Literal.- Rationale: Literal types are meant to be a
minimal extension to the PEP 484 typing ecosystem and requiring type
checkers to interpret potentially expressions inside types adds too
much complexity. Also see . - As a consequence, complex numbers like Literal and
Literal are also prohibited. For consistency, literals like
Literal that contain just a single complex number are also
prohibited. - The only exception to this rule is the unary - (minus) for ints: types
like Literal are accepted.
- Rationale: Literal types are meant to be a
- Tuples containing valid literal types like Literal.
The user could always express this type as
Tuple, Literal, Literal] instead. Also,
tuples are likely to be confused with the Literal
shortcut. - Mutable literal data structures like dict literals, list literals, or
set literals: literals are always implicitly final and immutable. So,
Literal is illegal. - Any other types: for example, Literal, or
Literal are illegal. This includes typevars: if
T is a typevar, Literal is not allowed. Typevars can vary over
only types, never over values.
The following are provisionally disallowed for simplicity. We can consider
allowing them in future extensions of this PEP.