chunk_id stringlengths 36 36 | source stringclasses 35
values | source_url stringlengths 0 290 | upstream_license stringclasses 1
value | document_id stringlengths 36 36 | chunk_index int64 0 324k | retrieved_at stringclasses 2
values | chunker_version stringclasses 4
values | content_hash stringlengths 15 64 | content stringlengths 50 44.7k | namespace stringclasses 9
values | source_name stringclasses 35
values | raw_text stringlengths 50 44.7k | cleaned_text stringlengths 50 44.7k | tags stringclasses 49
values | collection_name stringclasses 11
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b0553f91-9fa5-4285-bc70-5eebba35627e | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,140 | supabase-export-v2 | f74fa55572f64567 | .. code-block:: shell-session
$ python prog.py 4
Traceback (most recent call last):
File "prog.py", line 5, in <module>
print(args.square**2)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' | trusted_official_docs | CPython Docs | .. code-block:: shell-session
$ python prog.py 4
Traceback (most recent call last):
File "prog.py", line 5, in <module>
print(args.square**2)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' | .. code-block:: shell-session
$ python prog.py 4
Traceback (most recent call last):
File "prog.py", line 5, in <module>
print(args.square**2)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
b2156242-1c98-4ae4-8249-4865d5c3e733 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,234 | supabase-export-v2 | 1770d6942f4850c1 | >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('-n', nargs='+') >>> parser.add_argument('args', nargs='*')
>>> # ambiguous, so parse_args assumes it's an option
>>> parser.parse_args(['-f'])
usage: PROG [-h] [-n N [N ...]] [args ...]
PROG: error: unrecognized arguments: -f | trusted_official_docs | CPython Docs | >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('-n', nargs='+') >>> parser.add_argument('args', nargs='*')
>>> # ambiguous, so parse_args assumes it's an option
>>> parser.parse_args(['-f'])
usage: PROG [-h] [-n N [N ...]] [args ...]
PROG: error: unrecognized arguments: -f | >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('-n', nargs='+') >>> parser.add_argument('args', nargs='*')
>>> # ambiguous, so parse_args assumes it's an option
>>> parser.parse_args(['-f'])
usage: PROG [-h] [-n N [N ...]] [args ...]
PROG: error: unrecognized arguments: -f | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
b50e2b2c-2690-411d-9d18-e046019a6207 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,104 | supabase-export-v2 | 765413792ba01456 | basic usage is ``cp SRC DEST``. The first position is *what you want copied,* and the second position is *where you want it copied to*.
* Now, say we want to change behaviour of the program. In our example,
we display more info for each file instead of just showing the file names. The ``-l`` in that case is known as a... | trusted_official_docs | CPython Docs | basic usage is ``cp SRC DEST``. The first position is *what you want copied,* and the second position is *where you want it copied to*.
* Now, say we want to change behaviour of the program. In our example,
we display more info for each file instead of just showing the file names. The ``-l`` in that case is known as a... | basic usage is ``cp SRC DEST``. The first position is *what you want copied,* and the second position is *where you want it copied to*.
* Now, say we want to change behaviour of the program. In our example,
we display more info for each file instead of just showing the file names. The ``-l`` in that case is known as a... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
ba9c9b35-de93-465d-b5f2-a59bbb7febd4 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,242 | supabase-export-v2 | e2f9a707869e51be | = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true") parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent") args = parser.parse_ar... | trusted_official_docs | CPython Docs | = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true") parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent") args = parser.parse_ar... | = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true") parser.add_argument("x", type=int, help="the base") parser.add_argument("y", type=int, help="the exponent") args = parser.parse_ar... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
c1c84d24-e4f5-4a01-a8da-c0779d8193b9 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,239 | supabase-export-v2 | d9ce4d1935fb412d | Conflicting options -------------------
So far, we have been working with two methods of an
:class:`argparse.ArgumentParser` instance. Let's introduce a third one,
:meth:`~ArgumentParser.add_mutually_exclusive_group`. It allows for us to specify options that
conflict with each other. Let's also change the rest of the p... | trusted_official_docs | CPython Docs | Conflicting options -------------------
So far, we have been working with two methods of an
:class:`argparse.ArgumentParser` instance. Let's introduce a third one,
:meth:`~ArgumentParser.add_mutually_exclusive_group`. It allows for us to specify options that
conflict with each other. Let's also change the rest of the p... | Conflicting options -------------------
So far, we have been working with two methods of an
:class:`argparse.ArgumentParser` instance. Let's introduce a third one,
:meth:`~ArgumentParser.add_mutually_exclusive_group`. It allows for us to specify options that
conflict with each other. Let's also change the rest of the p... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
c8757a66-1776-4c01-b9b0-f0227e6edc4e | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,168 | supabase-export-v2 | afc5fac7f4d5b782 | Short options -------------
If you are familiar with command line usage,
you will notice that I haven't yet touched on the topic of short
versions of the options. It's quite simple:: | trusted_official_docs | CPython Docs | Short options -------------
If you are familiar with command line usage,
you will notice that I haven't yet touched on the topic of short
versions of the options. It's quite simple:: | Short options -------------
If you are familiar with command line usage,
you will notice that I haven't yet touched on the topic of short
versions of the options. It's quite simple:: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
d107b939-1d5c-41ea-98e0-464d4c31fca7 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,208 | supabase-export-v2 | 492377c59f9add34 | argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity") args = parser.parse_args() answer = args.square**2
# bugfix: replace == with >=
if args.verbosity >= ... | trusted_official_docs | CPython Docs | argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity") args = parser.parse_args() answer = args.square**2
# bugfix: replace == with >=
if args.verbosity >= ... | argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity") args = parser.parse_args() answer = args.square**2
# bugfix: replace == with >=
if args.verbosity >= ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
d53cae6d-5023-41dc-9496-7094a14703f0 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,126 | supabase-export-v2 | 7fa5154da6875fad | Here is what's happening:
* We've added the :meth:`~ArgumentParser.add_argument` method, which is what we use to specify
which command-line options the program is willing to accept. In this case,
I've named it ``echo`` so that it's in line with its function. | trusted_official_docs | CPython Docs | Here is what's happening:
* We've added the :meth:`~ArgumentParser.add_argument` method, which is what we use to specify
which command-line options the program is willing to accept. In this case,
I've named it ``echo`` so that it's in line with its function. | Here is what's happening:
* We've added the :meth:`~ArgumentParser.add_argument` method, which is what we use to specify
which command-line options the program is willing to accept. In this case,
I've named it ``echo`` so that it's in line with its function. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
d7e2546f-a912-4413-a691-e36b148607cd | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,131 | supabase-export-v2 | e07f58c80d31ca90 | but we don't know what it does, other than by guessing or by reading the source code. So, let's make it a bit more useful::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo) | trusted_official_docs | CPython Docs | but we don't know what it does, other than by guessing or by reading the source code. So, let's make it a bit more useful::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo) | but we don't know what it does, other than by guessing or by reading the source code. So, let's make it a bit more useful::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo) | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
d7f4ddcf-1d2b-42ef-9fd3-100a5ddf357c | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,100 | supabase-export-v2 | a76e6255516a5420 | .. code-block:: shell-session
$ ls
cpython devguide prog.py pypy rm-unused-function.patch
$ ls pypy
ctypes_configure demo dotviewer include lib_pypy lib-python ... $ ls -l
total 20
drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide
-rwxr-xr-x 1 wena wena 535 Feb 19... | trusted_official_docs | CPython Docs | .. code-block:: shell-session
$ ls
cpython devguide prog.py pypy rm-unused-function.patch
$ ls pypy
ctypes_configure demo dotviewer include lib_pypy lib-python ... $ ls -l
total 20
drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide
-rwxr-xr-x 1 wena wena 535 Feb 19... | .. code-block:: shell-session
$ ls
cpython devguide prog.py pypy rm-unused-function.patch
$ ls pypy
ctypes_configure demo dotviewer include lib_pypy lib-python ... $ ls -l
total 20
drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide
-rwxr-xr-x 1 wena wena 535 Feb 19... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
db006dee-5a7d-4385-b9ac-68f4723ec139 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,181 | supabase-export-v2 | 7b3e8748ac37ca53 | * Note that the order does not matter.
How about we give this program of ours back the ability to have
multiple verbosity values, and actually get to use them:: | trusted_official_docs | CPython Docs | * Note that the order does not matter.
How about we give this program of ours back the ability to have
multiple verbosity values, and actually get to use them:: | * Note that the order does not matter.
How about we give this program of ours back the ability to have
multiple verbosity values, and actually get to use them:: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
df618d47-806d-4c73-9d69-ec2c76fe5d68 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,196 | supabase-export-v2 | 481b9bb5d6577548 | .. code-block:: shell-session
$ python prog.py 4
16
$ python prog.py 4 -v
4^2 == 16
$ python prog.py 4 -vv
the square of 4 equals 16
$ python prog.py 4 --verbosity --verbosity
the square of 4 equals 16
$ python prog.py 4 -v 1
usage: prog.py [-h] [-v] square
prog.py: error: unrecognized arguments: 1
$ python ... | trusted_official_docs | CPython Docs | .. code-block:: shell-session
$ python prog.py 4
16
$ python prog.py 4 -v
4^2 == 16
$ python prog.py 4 -vv
the square of 4 equals 16
$ python prog.py 4 --verbosity --verbosity
the square of 4 equals 16
$ python prog.py 4 -v 1
usage: prog.py [-h] [-v] square
prog.py: error: unrecognized arguments: 1
$ python ... | .. code-block:: shell-session
$ python prog.py 4
16
$ python prog.py 4 -v
4^2 == 16
$ python prog.py 4 -vv
the square of 4 equals 16
$ python prog.py 4 --verbosity --verbosity
the square of 4 equals 16
$ python prog.py 4 -v 1
usage: prog.py [-h] [-v] square
prog.py: error: unrecognized arguments: 1
$ python ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
e11c0e2d-4d10-446e-bbe3-1d1c3e362722 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,277 | supabase-export-v2 | f5e440c46537fa92 | returns the converted value. However, if you need to handle more complex scenarios, you can use a custom action class with the **action** parameter instead.
For example, let's say you want to handle arguments with different prefixes and
process them accordingly:: | trusted_official_docs | CPython Docs | returns the converted value. However, if you need to handle more complex scenarios, you can use a custom action class with the **action** parameter instead.
For example, let's say you want to handle arguments with different prefixes and
process them accordingly:: | returns the converted value. However, if you need to handle more complex scenarios, you can use a custom action class with the **action** parameter instead.
For example, let's say you want to handle arguments with different prefixes and
process them accordingly:: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
e1fd9cbd-c6ac-4a5b-b3b5-81b819e0b674 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,161 | supabase-export-v2 | 09cf59396c139cd8 | .. code-block:: shell-session
$ python prog.py --verbose
verbosity turned on
$ python prog.py --verbose 1
usage: prog.py [-h] [--verbose]
prog.py: error: unrecognized arguments: 1
$ python prog.py --help
usage: prog.py [-h] [--verbose] | trusted_official_docs | CPython Docs | .. code-block:: shell-session
$ python prog.py --verbose
verbosity turned on
$ python prog.py --verbose 1
usage: prog.py [-h] [--verbose]
prog.py: error: unrecognized arguments: 1
$ python prog.py --help
usage: prog.py [-h] [--verbose] | .. code-block:: shell-session
$ python prog.py --verbose
verbosity turned on
$ python prog.py --verbose 1
usage: prog.py [-h] [--verbose]
prog.py: error: unrecognized arguments: 1
$ python prog.py --help
usage: prog.py [-h] [--verbose] | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
e3b7257a-e501-46e4-978f-2ec9956a12a4 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,218 | supabase-export-v2 | 0c72d9c43a8f5d30 | $ python prog.py 4 16
You can go quite far just with what we've learned so far,
and we have only scratched the surface. The :mod:`argparse` module is very powerful,
and we'll explore a bit more of it before we end this tutorial. | trusted_official_docs | CPython Docs | $ python prog.py 4 16
You can go quite far just with what we've learned so far,
and we have only scratched the surface. The :mod:`argparse` module is very powerful,
and we'll explore a bit more of it before we end this tutorial. | $ python prog.py 4 16
You can go quite far just with what we've learned so far,
and we have only scratched the surface. The :mod:`argparse` module is very powerful,
and we'll explore a bit more of it before we end this tutorial. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
e5a55849-4a15-4ad3-88ca-ae2d97e00150 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,226 | supabase-export-v2 | 3537b6a9f7531ed3 | options: -h, --help show this help message and exit -v, --verbosity $ python prog.py 4 2 -v 4^2 == 16
Notice that so far we've been using verbosity level to *change* the text
that gets displayed. The following example instead uses verbosity level
to display *more* text instead:: | trusted_official_docs | CPython Docs | options: -h, --help show this help message and exit -v, --verbosity $ python prog.py 4 2 -v 4^2 == 16
Notice that so far we've been using verbosity level to *change* the text
that gets displayed. The following example instead uses verbosity level
to display *more* text instead:: | options: -h, --help show this help message and exit -v, --verbosity $ python prog.py 4 2 -v 4^2 == 16
Notice that so far we've been using verbosity level to *change* the text
that gets displayed. The following example instead uses verbosity level
to display *more* text instead:: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
e6f68a11-3c92-4c44-ac20-c2efebad33e2 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,184 | supabase-export-v2 | b5b2811c5fbed0ca | .. code-block:: shell-session
$ python prog.py 4
16
$ python prog.py 4 -v
usage: prog.py [-h] [-v VERBOSITY] square
prog.py: error: argument -v/--verbosity: expected one argument
$ python prog.py 4 -v 1
4^2 == 16
$ python prog.py 4 -v 2
the square of 4 equals 16
$ python prog.py 4 -v 3
16 | trusted_official_docs | CPython Docs | .. code-block:: shell-session
$ python prog.py 4
16
$ python prog.py 4 -v
usage: prog.py [-h] [-v VERBOSITY] square
prog.py: error: argument -v/--verbosity: expected one argument
$ python prog.py 4 -v 1
4^2 == 16
$ python prog.py 4 -v 2
the square of 4 equals 16
$ python prog.py 4 -v 3
16 | .. code-block:: shell-session
$ python prog.py 4
16
$ python prog.py 4 -v
usage: prog.py [-h] [-v VERBOSITY] square
prog.py: error: argument -v/--verbosity: expected one argument
$ python prog.py 4 -v 1
4^2 == 16
$ python prog.py 4 -v 2
the square of 4 equals 16
$ python prog.py 4 -v 3
16 | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
e6fa5937-accd-46f3-90da-b4ca9243403a | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,246 | supabase-export-v2 | 679bd04eaa7377bb | -v/--verbose $ python prog.py 4 2 -v --quiet usage: prog.py [-h] [-v | -q] x y prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
That should be easy to follow. I've added that last output so you can see the
sort of flexibility you get, i.e. mixing long form options with short form
ones. | trusted_official_docs | CPython Docs | -v/--verbose $ python prog.py 4 2 -v --quiet usage: prog.py [-h] [-v | -q] x y prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
That should be easy to follow. I've added that last output so you can see the
sort of flexibility you get, i.e. mixing long form options with short form
ones. | -v/--verbose $ python prog.py 4 2 -v --quiet usage: prog.py [-h] [-v | -q] x y prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
That should be easy to follow. I've added that last output so you can see the
sort of flexibility you get, i.e. mixing long form options with short form
ones. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
ec8a20b3-9a89-423b-9a47-dc2fed8d155d | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,176 | supabase-export-v2 | 42de5e250152d570 | Our program keeps growing in complexity::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
help="increase output verbosity")
args = parser.parse_args()
answer = args.sq... | trusted_official_docs | CPython Docs | Our program keeps growing in complexity::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
help="increase output verbosity")
args = parser.parse_args()
answer = args.sq... | Our program keeps growing in complexity::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
help="increase output verbosity")
args = parser.parse_args()
answer = args.sq... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
f141eadb-b7f2-452d-bf4b-b78584785402 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,221 | supabase-export-v2 | fa5971bac0bdcd83 | What if we wanted to expand our tiny program to perform other powers, not just squares::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
... | trusted_official_docs | CPython Docs | What if we wanted to expand our tiny program to perform other powers, not just squares::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
... | What if we wanted to expand our tiny program to perform other powers, not just squares::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
f2b81c43-3747-4537-82b5-44677799e713 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,211 | supabase-export-v2 | 91cc9f71608a1c37 | .. code-block:: shell-session
$ python prog.py 4 -vvv
the square of 4 equals 16
$ python prog.py 4 -vvvv
the square of 4 equals 16
$ python prog.py 4
Traceback (most recent call last):
File "prog.py", line 11, in <module>
if args.verbosity >= 2:
TypeError: '>=' not supported between instances of 'NoneType' and ... | trusted_official_docs | CPython Docs | .. code-block:: shell-session
$ python prog.py 4 -vvv
the square of 4 equals 16
$ python prog.py 4 -vvvv
the square of 4 equals 16
$ python prog.py 4
Traceback (most recent call last):
File "prog.py", line 11, in <module>
if args.verbosity >= 2:
TypeError: '>=' not supported between instances of 'NoneType' and ... | .. code-block:: shell-session
$ python prog.py 4 -vvv
the square of 4 equals 16
$ python prog.py 4 -vvvv
the square of 4 equals 16
$ python prog.py 4
Traceback (most recent call last):
File "prog.py", line 11, in <module>
if args.verbosity >= 2:
TypeError: '>=' not supported between instances of 'NoneType' and ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
f2d6fe62-f165-4f3e-bdbc-c944ce0f4eb1 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,115 | supabase-export-v2 | c909ff8a06f3d432 | * Running the script without any options results in nothing displayed to stdout. Not so useful.
* The second one starts to display the usefulness of the :mod:`argparse`
module. We have done almost nothing, but already we get a nice help message. | trusted_official_docs | CPython Docs | * Running the script without any options results in nothing displayed to stdout. Not so useful.
* The second one starts to display the usefulness of the :mod:`argparse`
module. We have done almost nothing, but already we get a nice help message. | * Running the script without any options results in nothing displayed to stdout. Not so useful.
* The second one starts to display the usefulness of the :mod:`argparse`
module. We have done almost nothing, but already we get a nice help message. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
f2fa08fa-ab86-473b-9967-4193e48ed31e | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,112 | supabase-export-v2 | 0b86e36e269f8cb5 | $ python prog.py $ python prog.py --help usage: prog.py [-h]
options:
-h, --help show this help message and exit
$ python prog.py --verbose
usage: prog.py [-h]
prog.py: error: unrecognized arguments: --verbose
$ python prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo | trusted_official_docs | CPython Docs | $ python prog.py $ python prog.py --help usage: prog.py [-h]
options:
-h, --help show this help message and exit
$ python prog.py --verbose
usage: prog.py [-h]
prog.py: error: unrecognized arguments: --verbose
$ python prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo | $ python prog.py $ python prog.py --help usage: prog.py [-h]
options:
-h, --help show this help message and exit
$ python prog.py --verbose
usage: prog.py [-h]
prog.py: error: unrecognized arguments: --verbose
$ python prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
f8b4f9f1-317f-449b-9513-7657d823f572 | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,182 | supabase-export-v2 | 1f90700a1387dada | How about we give this program of ours back the ability to have multiple verbosity values, and actually get to use them::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int,
help="in... | trusted_official_docs | CPython Docs | How about we give this program of ours back the ability to have multiple verbosity values, and actually get to use them::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int,
help="in... | How about we give this program of ours back the ability to have multiple verbosity values, and actually get to use them::
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int,
help="in... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
fd6b8dd4-f865-45cf-9005-3a891e600a9e | CPython Docs | file://datasets/cpython/Doc/howto/argparse.rst | unknown | 6466631f-3432-49bd-ad66-8e150a30fc13 | 58,276 | supabase-export-v2 | 305f7f7a04126a32 | input before it's stored in the :class:`argparse.Namespace`. This can be useful when you need to pre-process the input before it is used in your program.
When using a custom type converter, you can use any callable that takes a
single string argument (the argument value) and returns the converted value. However, if you... | trusted_official_docs | CPython Docs | input before it's stored in the :class:`argparse.Namespace`. This can be useful when you need to pre-process the input before it is used in your program.
When using a custom type converter, you can use any callable that takes a
single string argument (the argument value) and returns the converted value. However, if you... | input before it's stored in the :class:`argparse.Namespace`. This can be useful when you need to pre-process the input before it is used in your program.
When using a custom type converter, you can use any callable that takes a
single string argument (the argument value) and returns the converted value. However, if you... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
769a3c31-eb94-4e02-9ec5-ca620abb9886 | CPython Docs | file://datasets/cpython/Doc/howto/cporting.rst | unknown | 7efface5-c106-4b5d-ab02-00b47d1a628f | 58,292 | supabase-export-v2 | 1b4f851774a57c9a | C API. Extensions generally need to be re-written to use one of them, but the library then handles differences between various Python versions and implementations.
.. _Migrating C extensions: http://python3porting.com/cextensions.html
.. _Porting guide: https://py3c.readthedocs.io/en/latest/guide.html | trusted_official_docs | CPython Docs | C API. Extensions generally need to be re-written to use one of them, but the library then handles differences between various Python versions and implementations.
.. _Migrating C extensions: http://python3porting.com/cextensions.html
.. _Porting guide: https://py3c.readthedocs.io/en/latest/guide.html | C API. Extensions generally need to be re-written to use one of them, but the library then handles differences between various Python versions and implementations.
.. _Migrating C extensions: http://python3porting.com/cextensions.html
.. _Porting guide: https://py3c.readthedocs.io/en/latest/guide.html | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
c60fc003-bd35-4a15-982b-d629e99f4c9f | CPython Docs | file://datasets/cpython/Doc/howto/cporting.rst | unknown | 7efface5-c106-4b5d-ab02-00b47d1a628f | 58,291 | supabase-export-v2 | d32d1c80cae59080 | We recommend the following resources for porting extension modules to Python 3:
* The `Migrating C extensions`_ chapter from
*Supporting Python 3: An in-depth guide*, a book on moving from Python 2
to Python 3 in general, guides the reader through porting an extension
module. * The `Porting guide`_ from the *py3c* p... | trusted_official_docs | CPython Docs | We recommend the following resources for porting extension modules to Python 3:
* The `Migrating C extensions`_ chapter from
*Supporting Python 3: An in-depth guide*, a book on moving from Python 2
to Python 3 in general, guides the reader through porting an extension
module. * The `Porting guide`_ from the *py3c* p... | We recommend the following resources for porting extension modules to Python 3:
* The `Migrating C extensions`_ chapter from
*Supporting Python 3: An in-depth guide*, a book on moving from Python 2
to Python 3 in general, guides the reader through porting an extension
module. * The `Porting guide`_ from the *py3c* p... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
00bed681-67d3-415f-9b21-38797ea16451 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,526 | supabase-export-v2 | f372b78e6b8cea29 | Pure Python Equivalents ^^^^^^^^^^^^^^^^^^^^^^^
The descriptor protocol is simple and offers exciting possibilities. Several
use cases are so common that they have been prepackaged into built-in tools. Properties, bound methods, static methods, class methods, and \_\_slots\_\_ are
all based on the descriptor protocol. | trusted_official_docs | CPython Docs | Pure Python Equivalents ^^^^^^^^^^^^^^^^^^^^^^^
The descriptor protocol is simple and offers exciting possibilities. Several
use cases are so common that they have been prepackaged into built-in tools. Properties, bound methods, static methods, class methods, and \_\_slots\_\_ are
all based on the descriptor protocol. | Pure Python Equivalents ^^^^^^^^^^^^^^^^^^^^^^^
The descriptor protocol is simple and offers exciting possibilities. Several
use cases are so common that they have been prepackaged into built-in tools. Properties, bound methods, static methods, class methods, and \_\_slots\_\_ are
all based on the descriptor protocol. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0424b6a1-7334-410b-826b-2d035793e52b | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,651 | supabase-export-v2 | 740184009828d670 | a class defines ``__slots__``, it replaces instance dictionaries with a fixed-length array of slot values. From a user point of view that has several effects:
1. Provides immediate detection of bugs due to misspelled attribute
assignments. Only attribute names specified in ``__slots__`` are allowed: | trusted_official_docs | CPython Docs | a class defines ``__slots__``, it replaces instance dictionaries with a fixed-length array of slot values. From a user point of view that has several effects:
1. Provides immediate detection of bugs due to misspelled attribute
assignments. Only attribute names specified in ``__slots__`` are allowed: | a class defines ``__slots__``, it replaces instance dictionaries with a fixed-length array of slot values. From a user point of view that has several effects:
1. Provides immediate detection of bugs due to misspelled attribute
assignments. Only attribute names specified in ``__slots__`` are allowed: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
09f583d7-60a9-4a9a-8d40-de855098a6c4 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,501 | supabase-export-v2 | 98844b2e785ebdd1 | The following code is a simplified skeleton showing how data descriptors could be used to implement an `object relational mapping <https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping>`_.
The essential idea is that the data is stored in an external database. The
Python instances only hold keys to the databas... | trusted_official_docs | CPython Docs | The following code is a simplified skeleton showing how data descriptors could be used to implement an `object relational mapping <https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping>`_.
The essential idea is that the data is stored in an external database. The
Python instances only hold keys to the databas... | The following code is a simplified skeleton showing how data descriptors could be used to implement an `object relational mapping <https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping>`_.
The essential idea is that the data is stored in an external database. The
Python instances only hold keys to the databas... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0af1fa97-5ba4-4e01-bd4b-03568785375e | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,468 | supabase-export-v2 | fd7d9d48e92d0fdd | .. doctest:: :hide:
>>> a = DualOperator(11)
>>> vars(a).update(p3 = '_p3', m7 = '_m7')
>>> a.x == a['x'] == 10
True
>>> a.z == a['z'] == 11
True
>>> a.p2 == a['p2'] == 20
True
>>> a.p3 == a['p3'] == 30
True
>>> a.m5(100) == a.m5(100) == 500
True
>>> a.m7 == a['m7'] == '_m7'
True
>>> a.g == a['g'] == ('ge... | trusted_official_docs | CPython Docs | .. doctest:: :hide:
>>> a = DualOperator(11)
>>> vars(a).update(p3 = '_p3', m7 = '_m7')
>>> a.x == a['x'] == 10
True
>>> a.z == a['z'] == 11
True
>>> a.p2 == a['p2'] == 20
True
>>> a.p3 == a['p3'] == 30
True
>>> a.m5(100) == a.m5(100) == 500
True
>>> a.m7 == a['m7'] == '_m7'
True
>>> a.g == a['g'] == ('ge... | .. doctest:: :hide:
>>> a = DualOperator(11)
>>> vars(a).update(p3 = '_p3', m7 = '_m7')
>>> a.x == a['x'] == 10
True
>>> a.z == a['z'] == 11
True
>>> a.p2 == a['p2'] == 20
True
>>> a.p3 == a['p3'] == 30
True
>>> a.m5(100) == a.m5(100) == 500
True
>>> a.m7 == a['m7'] == '_m7'
True
>>> a.g == a['g'] == ('ge... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0be6a7fd-f105-4c24-9b56-0053428eafa1 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,666 | supabase-export-v2 | 21614fd02498f65c | 4. Improves speed. Reading instance variables is 35% faster with ``__slots__`` (as measured with Python 3.10 on an Apple M1 processor).
5. Blocks tools like :func:`functools.cached_property` which require an
instance dictionary to function correctly: | trusted_official_docs | CPython Docs | 4. Improves speed. Reading instance variables is 35% faster with ``__slots__`` (as measured with Python 3.10 on an Apple M1 processor).
5. Blocks tools like :func:`functools.cached_property` which require an
instance dictionary to function correctly: | 4. Improves speed. Reading instance variables is 35% faster with ``__slots__`` (as measured with Python 3.10 on an Apple M1 processor).
5. Blocks tools like :func:`functools.cached_property` which require an
instance dictionary to function correctly: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0c7b081a-2ef4-447d-bc8f-e73074fa824d | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,396 | supabase-export-v2 | 3cf18698b2b52461 | 1) :class:`!OneOf` verifies that a value is one of a restricted set of options.
2) :class:`!Number` verifies that a value is either an :class:`int` or
:class:`float`. Optionally, it verifies that a value is between a given
minimum or maximum. | trusted_official_docs | CPython Docs | 1) :class:`!OneOf` verifies that a value is one of a restricted set of options.
2) :class:`!Number` verifies that a value is either an :class:`int` or
:class:`float`. Optionally, it verifies that a value is between a given
minimum or maximum. | 1) :class:`!OneOf` verifies that a value is one of a restricted set of options.
2) :class:`!Number` verifies that a value is either an :class:`int` or
:class:`float`. Optionally, it verifies that a value is between a given
minimum or maximum. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
0e41d0ca-cb2e-43e9-88cc-7439cb1706a7 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,664 | supabase-export-v2 | 0c9c4dfa600b21b9 | property 'dept' of 'Immutable' object has no setter >>> mark.location = 'Mars' Traceback (most recent call last): ... AttributeError: 'Immutable' object has no attribute 'location'
3. Saves memory. On a 64-bit Linux build, an instance with two attributes
takes 48 bytes with ``__slots__`` and 152 bytes without. This `fl... | trusted_official_docs | CPython Docs | property 'dept' of 'Immutable' object has no setter >>> mark.location = 'Mars' Traceback (most recent call last): ... AttributeError: 'Immutable' object has no attribute 'location'
3. Saves memory. On a 64-bit Linux build, an instance with two attributes
takes 48 bytes with ``__slots__`` and 152 bytes without. This `fl... | property 'dept' of 'Immutable' object has no setter >>> mark.location = 'Mars' Traceback (most recent call last): ... AttributeError: 'Immutable' object has no attribute 'location'
3. Saves memory. On a 64-bit Linux build, an instance with two attributes
takes 48 bytes with ``__slots__`` and 152 bytes without. This `fl... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
11637af6-e1a5-4351-9203-4cc8efd39002 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,621 | supabase-export-v2 | 3b7d7ffe31205893 | >>> E_sim.f(3) '!!!' >>> E_sim().f(3) '!!!'
>>> sm = vars(E_sim)['f']
>>> type(sm).__name__
'StaticMethod'
>>> f = E_sim.f
>>> type(f).__name__
'function'
>>> sm.__name__
'f'
>>> f.__name__
'f'
>>> sm.__qualname__
'E_sim.f'
>>> f.__qualname__
'E_sim.f'
>>> sm.__doc__
'Simple function example'
>>> f.__do... | trusted_official_docs | CPython Docs | >>> E_sim.f(3) '!!!' >>> E_sim().f(3) '!!!'
>>> sm = vars(E_sim)['f']
>>> type(sm).__name__
'StaticMethod'
>>> f = E_sim.f
>>> type(f).__name__
'function'
>>> sm.__name__
'f'
>>> f.__name__
'f'
>>> sm.__qualname__
'E_sim.f'
>>> f.__qualname__
'E_sim.f'
>>> sm.__doc__
'Simple function example'
>>> f.__do... | >>> E_sim.f(3) '!!!' >>> E_sim().f(3) '!!!'
>>> sm = vars(E_sim)['f']
>>> type(sm).__name__
'StaticMethod'
>>> f = E_sim.f
>>> type(f).__name__
'function'
>>> sm.__name__
'f'
>>> f.__name__
'f'
>>> sm.__qualname__
'E_sim.f'
>>> f.__qualname__
'E_sim.f'
>>> sm.__doc__
'Simple function example'
>>> f.__do... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
11ada6da-8dd7-4478-8c28-4d3e9d89cdee | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,385 | supabase-export-v2 | b6a7f8ed57b94589 | the new value meets various type and range restrictions. If those restrictions aren't met, it raises an exception to prevent data corruption at its source.
This :class:`!Validator` class is both an :term:`abstract base class` and a
managed attribute descriptor: | trusted_official_docs | CPython Docs | the new value meets various type and range restrictions. If those restrictions aren't met, it raises an exception to prevent data corruption at its source.
This :class:`!Validator` class is both an :term:`abstract base class` and a
managed attribute descriptor: | the new value meets various type and range restrictions. If those restrictions aren't met, it raises an exception to prevent data corruption at its source.
This :class:`!Validator` class is both an :term:`abstract base class` and a
managed attribute descriptor: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
11d49204-d81d-44be-9908-c357be7ad497 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,298 | supabase-export-v2 | 68ff5e7e7e74b1a0 | This guide has four major sections:
1) The "primer" gives a basic overview, moving gently from simple examples,
adding one feature at a time. Start here if you're new to descriptors. | trusted_official_docs | CPython Docs | This guide has four major sections:
1) The "primer" gives a basic overview, moving gently from simple examples,
adding one feature at a time. Start here if you're new to descriptors. | This guide has four major sections:
1) The "primer" gives a basic overview, moving gently from simple examples,
adding one feature at a time. Start here if you're new to descriptors. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
120e5b30-2cb7-4457-b69e-3866da7e7a64 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,555 | supabase-export-v2 | 093b7704cdf6ac5c | >>> cc = CC() >>> cc.x = 33 >>> try: ... cc.no_getter ... except AttributeError as e: ... type(e).__name__ ... 'AttributeError'
>>> try:
... cc.no_setter = 33
... except AttributeError as e:
... type(e).__name__
... 'AttributeError' | trusted_official_docs | CPython Docs | >>> cc = CC() >>> cc.x = 33 >>> try: ... cc.no_getter ... except AttributeError as e: ... type(e).__name__ ... 'AttributeError'
>>> try:
... cc.no_setter = 33
... except AttributeError as e:
... type(e).__name__
... 'AttributeError' | >>> cc = CC() >>> cc.x = 33 >>> try: ... cc.no_getter ... except AttributeError as e: ... type(e).__name__ ... 'AttributeError'
>>> try:
... cc.no_setter = 33
... except AttributeError as e:
... type(e).__name__
... 'AttributeError' | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
126f967f-cb0e-498c-ab26-4b5b7254128a | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,629 | supabase-export-v2 | 432226f0d9800cc7 | >>> F.f(3) ('F', 3) >>> F().f(3) ('F', 3)
This behavior is useful whenever the method only needs to have a class
reference and does not rely on data stored in a specific instance. One use for
class methods is to create alternate class constructors. For example, the
classmethod :func:`dict.fromkeys` creates a new dictio... | trusted_official_docs | CPython Docs | >>> F.f(3) ('F', 3) >>> F().f(3) ('F', 3)
This behavior is useful whenever the method only needs to have a class
reference and does not rely on data stored in a specific instance. One use for
class methods is to create alternate class constructors. For example, the
classmethod :func:`dict.fromkeys` creates a new dictio... | >>> F.f(3) ('F', 3) >>> F().f(3) ('F', 3)
This behavior is useful whenever the method only needs to have a class
reference and does not rely on data stored in a specific instance. One use for
class methods is to create alternate class constructors. For example, the
classmethod :func:`dict.fromkeys` creates a new dictio... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
15d51bcb-3cb6-44bf-a0bf-2a5de8fad72b | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,541 | supabase-export-v2 | 6b24622fd4999d13 | def __get__(self, obj, objtype=None): if obj is None: return self if self.fget is None: raise AttributeError return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError
self.fset(obj, value) | trusted_official_docs | CPython Docs | def __get__(self, obj, objtype=None): if obj is None: return self if self.fget is None: raise AttributeError return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError
self.fset(obj, value) | def __get__(self, obj, objtype=None): if obj is None: return self if self.fget is None: raise AttributeError return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError
self.fset(obj, value) | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
18a4aff8-b253-4266-bdbb-297a5a16c5da | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,698 | supabase-export-v2 | 1f25651ba1c2a9e1 | .. doctest:: :hide:
# We test this separately because the preceding section is not
# doctestable due to the hex memory address for the __init__ function
>>> isinstance(vars(H)['x'], Member)
True
>>> isinstance(vars(H)['y'], Member)
True | trusted_official_docs | CPython Docs | .. doctest:: :hide:
# We test this separately because the preceding section is not
# doctestable due to the hex memory address for the __init__ function
>>> isinstance(vars(H)['x'], Member)
True
>>> isinstance(vars(H)['y'], Member)
True | .. doctest:: :hide:
# We test this separately because the preceding section is not
# doctestable due to the hex memory address for the __init__ function
>>> isinstance(vars(H)['x'], Member)
True
>>> isinstance(vars(H)['y'], Member)
True | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1aeb5f37-68c0-462f-936a-05b9da73d286 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,600 | supabase-export-v2 | cd00af9e255e4e86 | Static methods --------------
Static methods return the underlying function without changes. Calling either
``c.f`` or ``C.f`` is the equivalent of a direct lookup into
``object.__getattribute__(c, "f")`` or ``object.__getattribute__(C, "f")``. As a
result, the function becomes identically accessible from either an obj... | trusted_official_docs | CPython Docs | Static methods --------------
Static methods return the underlying function without changes. Calling either
``c.f`` or ``C.f`` is the equivalent of a direct lookup into
``object.__getattribute__(c, "f")`` or ``object.__getattribute__(C, "f")``. As a
result, the function becomes identically accessible from either an obj... | Static methods --------------
Static methods return the underlying function without changes. Calling either
``c.f`` or ``C.f`` is the equivalent of a direct lookup into
``object.__getattribute__(c, "f")`` or ``object.__getattribute__(C, "f")``. As a
result, the function becomes identically accessible from either an obj... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1b576fd1-454e-4b21-95d9-f74ae6704072 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,380 | supabase-export-v2 | 06e7dfd88b74261f | the calling class controls what happens during lookup. Descriptors invert that relationship and allow the data being looked-up to have a say in the matter.
Descriptors are used throughout the language. It is how functions turn into
bound methods. Common tools like :func:`classmethod`, :func:`staticmethod`,
:func:`prope... | trusted_official_docs | CPython Docs | the calling class controls what happens during lookup. Descriptors invert that relationship and allow the data being looked-up to have a say in the matter.
Descriptors are used throughout the language. It is how functions turn into
bound methods. Common tools like :func:`classmethod`, :func:`staticmethod`,
:func:`prope... | the calling class controls what happens during lookup. Descriptors invert that relationship and allow the data being looked-up to have a say in the matter.
Descriptors are used throughout the language. It is how functions turn into
bound methods. Common tools like :func:`classmethod`, :func:`staticmethod`,
:func:`prope... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1c771f24-6859-4236-845a-45d2e5203c91 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,641 | supabase-export-v2 | c379971d012a7b72 | .. testcode:: :hide:
# Verify the emulation works
class T:
@ClassMethod
def cm(cls, x: int, y: str) -> tuple[str, int, str]:
"Class method that returns a tuple"
return (cls.__name__, x, y) | trusted_official_docs | CPython Docs | .. testcode:: :hide:
# Verify the emulation works
class T:
@ClassMethod
def cm(cls, x: int, y: str) -> tuple[str, int, str]:
"Class method that returns a tuple"
return (cls.__name__, x, y) | .. testcode:: :hide:
# Verify the emulation works
class T:
@ClassMethod
def cm(cls, x: int, y: str) -> tuple[str, int, str]:
"Class method that returns a tuple"
return (cls.__name__, x, y) | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1ccf65b7-7956-47b1-942c-14d1f29461a8 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,348 | supabase-export-v2 | 4bee9451fc6e251d | >>> dave.name # Regular attribute lookup isn't logged 'David D' >>> dave.age # Only the managed attribute is logged INFO:root:Accessing 'age' giving 40 40
One major issue with this example is that the private name *_age* is hardwired in
the *LoggedAgeAccess* class. That means that each instance can only have one
logged... | trusted_official_docs | CPython Docs | >>> dave.name # Regular attribute lookup isn't logged 'David D' >>> dave.age # Only the managed attribute is logged INFO:root:Accessing 'age' giving 40 40
One major issue with this example is that the private name *_age* is hardwired in
the *LoggedAgeAccess* class. That means that each instance can only have one
logged... | >>> dave.name # Regular attribute lookup isn't logged 'David D' >>> dave.age # Only the managed attribute is logged INFO:root:Accessing 'age' giving 40 40
One major issue with this example is that the private name *_age* is hardwired in
the *LoggedAgeAccess* class. That means that each instance can only have one
logged... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
1fc36437-5062-482a-8ebc-5da00c76d11f | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,406 | supabase-export-v2 | 4b8baaf055f52b03 | def __init__(self, minsize=None, maxsize=None, predicate=None): self.minsize = minsize self.maxsize = maxsize self.predicate = predicate
def validate(self, value):
if not isinstance(value, str):
raise TypeError(f'Expected {value!r} to be a str')
if self.minsize is not None and len(value) < self.minsize:
raise Value... | trusted_official_docs | CPython Docs | def __init__(self, minsize=None, maxsize=None, predicate=None): self.minsize = minsize self.maxsize = maxsize self.predicate = predicate
def validate(self, value):
if not isinstance(value, str):
raise TypeError(f'Expected {value!r} to be a str')
if self.minsize is not None and len(value) < self.minsize:
raise Value... | def __init__(self, minsize=None, maxsize=None, predicate=None): self.minsize = minsize self.maxsize = maxsize self.predicate = predicate
def validate(self, value):
if not isinstance(value, str):
raise TypeError(f'Expected {value!r} to be a str')
if self.minsize is not None and len(value) < self.minsize:
raise Value... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2198655e-2c97-48bc-af03-67793836984d | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,577 | supabase-export-v2 | 6d0a7574cbac0a72 | def __get__(self, obj, objtype=None): "Simulate func_descr_get() in Objects/funcobject.c" if obj is None: return self return MethodType(self, obj)
Running the following class in the interpreter shows how the function
descriptor works in practice: | trusted_official_docs | CPython Docs | def __get__(self, obj, objtype=None): "Simulate func_descr_get() in Objects/funcobject.c" if obj is None: return self return MethodType(self, obj)
Running the following class in the interpreter shows how the function
descriptor works in practice: | def __get__(self, obj, objtype=None): "Simulate func_descr_get() in Objects/funcobject.c" if obj is None: return self return MethodType(self, obj)
Running the following class in the interpreter shows how the function
descriptor works in practice: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
23c292f0-cf52-48e2-9dc6-82302699039e | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,687 | supabase-export-v2 | d585158f04d6eb65 | class Object: 'Simulate how object.__new__() allocates memory for __slots__'
def __new__(cls, *args, **kwargs):
'Emulate object_new() in Objects/typeobject.c'
inst = super().__new__(cls)
if hasattr(cls, 'slot_names'):
empty_slots = [null] * len(cls.slot_names)
object.__setattr__(inst, '_slotvalues', empty_slots)
... | trusted_official_docs | CPython Docs | class Object: 'Simulate how object.__new__() allocates memory for __slots__'
def __new__(cls, *args, **kwargs):
'Emulate object_new() in Objects/typeobject.c'
inst = super().__new__(cls)
if hasattr(cls, 'slot_names'):
empty_slots = [null] * len(cls.slot_names)
object.__setattr__(inst, '_slotvalues', empty_slots)
... | class Object: 'Simulate how object.__new__() allocates memory for __slots__'
def __new__(cls, *args, **kwargs):
'Emulate object_new() in Objects/typeobject.c'
inst = super().__new__(cls)
if hasattr(cls, 'slot_names'):
empty_slots = [null] * len(cls.slot_names)
object.__setattr__(inst, '_slotvalues', empty_slots)
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
282497a5-3ecc-42f9-9e36-ca610a97e4a9 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,624 | supabase-export-v2 | 7c62ea489bb46cd9 | Class methods -------------
Unlike static methods, class methods prepend the class reference to the
argument list before calling the function. This format is the same
for whether the caller is an object or a class: | trusted_official_docs | CPython Docs | Class methods -------------
Unlike static methods, class methods prepend the class reference to the
argument list before calling the function. This format is the same
for whether the caller is an object or a class: | Class methods -------------
Unlike static methods, class methods prepend the class reference to the
argument list before calling the function. This format is the same
for whether the caller is an object or a class: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2918836a-19af-4548-9b09-4c0a75f270b9 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,327 | supabase-export-v2 | bed39b035fb72a65 | >>> g.size # The games directory has three files 3 >>> os.remove('games/chess') # Delete a game >>> g.size # File count is automatically updated 2
Besides showing how descriptors can run computations, this example also
reveals the purpose of the parameters to :meth:`~object.__get__`. The *self*
parameter is *size*, an ... | trusted_official_docs | CPython Docs | >>> g.size # The games directory has three files 3 >>> os.remove('games/chess') # Delete a game >>> g.size # File count is automatically updated 2
Besides showing how descriptors can run computations, this example also
reveals the purpose of the parameters to :meth:`~object.__get__`. The *self*
parameter is *size*, an ... | >>> g.size # The games directory has three files 3 >>> os.remove('games/chess') # Delete a game >>> g.size # File count is automatically updated 2
Besides showing how descriptors can run computations, this example also
reveals the purpose of the parameters to :meth:`~object.__get__`. The *self*
parameter is *size*, an ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
291bce07-b663-44f4-b83a-ac8c3962826d | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,472 | supabase-export-v2 | 8bc13eaee135b9a7 | Note, there is no :meth:`~object.__getattr__` hook in the :meth:`~object.__getattribute__` code. That is why calling :meth:`~object.__getattribute__` directly or with ``super().__getattribute__`` will bypass :meth:`~object.__getattr__` entirely.
Instead, it is the dot operator and the :func:`getattr` function that are
... | trusted_official_docs | CPython Docs | Note, there is no :meth:`~object.__getattr__` hook in the :meth:`~object.__getattribute__` code. That is why calling :meth:`~object.__getattribute__` directly or with ``super().__getattribute__`` will bypass :meth:`~object.__getattr__` entirely.
Instead, it is the dot operator and the :func:`getattr` function that are
... | Note, there is no :meth:`~object.__getattr__` hook in the :meth:`~object.__getattribute__` code. That is why calling :meth:`~object.__getattribute__` directly or with ``super().__getattribute__`` will bypass :meth:`~object.__getattr__` entirely.
Instead, it is the dot operator and the :func:`getattr` function that are
... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2b35a25b-f6b4-47f1-a655-463f83aee4f4 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,647 | supabase-export-v2 | 795ab2d1af8f8a01 | T.cm.__name__ 'cm' >>> T.cm.__qualname__ 'T.cm' >>> T.cm.__doc__ 'Class method that returns a tuple' >>> T.cm.__annotations__ {'x': <class 'int'>, 'y': <class 'str'>, 'return': tuple[str, int, str]}
# Verify that __wrapped__ was added and works correctly
>>> f = vars(T)['cm'].__wrapped__
>>> type(f).__name__
'functi... | trusted_official_docs | CPython Docs | T.cm.__name__ 'cm' >>> T.cm.__qualname__ 'T.cm' >>> T.cm.__doc__ 'Class method that returns a tuple' >>> T.cm.__annotations__ {'x': <class 'int'>, 'y': <class 'str'>, 'return': tuple[str, int, str]}
# Verify that __wrapped__ was added and works correctly
>>> f = vars(T)['cm'].__wrapped__
>>> type(f).__name__
'functi... | T.cm.__name__ 'cm' >>> T.cm.__qualname__ 'T.cm' >>> T.cm.__doc__ 'Class method that returns a tuple' >>> T.cm.__annotations__ {'x': <class 'int'>, 'y': <class 'str'>, 'return': tuple[str, int, str]}
# Verify that __wrapped__ was added and works correctly
>>> f = vars(T)['cm'].__wrapped__
>>> type(f).__name__
'functi... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2cc36504-d5c2-42b9-8288-90efabd6688e | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,315 | supabase-export-v2 | 330eb2c971544092 | in the class dictionary. In the ``a.y`` lookup, the dot operator finds a descriptor instance, recognized by its ``__get__`` method. Calling that method returns ``10``.
Note that the value ``10`` is not stored in either the class dictionary or the
instance dictionary. Instead, the value ``10`` is computed on demand. | trusted_official_docs | CPython Docs | in the class dictionary. In the ``a.y`` lookup, the dot operator finds a descriptor instance, recognized by its ``__get__`` method. Calling that method returns ``10``.
Note that the value ``10`` is not stored in either the class dictionary or the
instance dictionary. Instead, the value ``10`` is computed on demand. | in the class dictionary. In the ``a.y`` lookup, the dot operator finds a descriptor instance, recognized by its ``__get__`` method. Calling that method returns ``10``.
Note that the value ``10`` is not stored in either the class dictionary or the
instance dictionary. Instead, the value ``10`` is computed on demand. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2d293398-1203-48d4-b428-d746d7bcfc5a | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,360 | supabase-export-v2 | 4c9e47e7ff10f485 | name = LoggedAccess() # First descriptor instance age = LoggedAccess() # Second descriptor instance
def __init__(self, name, age):
self.name = name # Calls the first descriptor
self.age = age # Calls the second descriptor | trusted_official_docs | CPython Docs | name = LoggedAccess() # First descriptor instance age = LoggedAccess() # Second descriptor instance
def __init__(self, name, age):
self.name = name # Calls the first descriptor
self.age = age # Calls the second descriptor | name = LoggedAccess() # First descriptor instance age = LoggedAccess() # Second descriptor instance
def __init__(self, name, age):
self.name = name # Calls the first descriptor
self.age = age # Calls the second descriptor | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
2ea3ec7a-4863-4353-bfb3-fa93dbefd1f4 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,362 | supabase-export-v2 | 0480d2889a017b67 | def birthday(self): self.age += 1
An interactive session shows that the :class:`!Person` class has called
:meth:`~object.__set_name__` so that the field names would be recorded. Here
we call :func:`vars` to look up the descriptor without triggering it: | trusted_official_docs | CPython Docs | def birthday(self): self.age += 1
An interactive session shows that the :class:`!Person` class has called
:meth:`~object.__set_name__` so that the field names would be recorded. Here
we call :func:`vars` to look up the descriptor without triggering it: | def birthday(self): self.age += 1
An interactive session shows that the :class:`!Person` class has called
:meth:`~object.__set_name__` so that the field names would be recorded. Here
we call :func:`vars` to look up the descriptor without triggering it: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
31c5c36d-5d53-45ff-b0ce-9674e537e6dd | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,345 | supabase-export-v2 | f02f1672fccc794f | = Person('Mary M', 30) # The initial age update is logged INFO:root:Updating 'age' to 30 >>> dave = Person('David D', 40) INFO:root:Updating 'age' to 40
>>> vars(mary) # The actual data is in a private attribute
{'name': 'Mary M', '_age': 30}
>>> vars(dave)
{'name': 'David D', '_age': 40} | trusted_official_docs | CPython Docs | = Person('Mary M', 30) # The initial age update is logged INFO:root:Updating 'age' to 30 >>> dave = Person('David D', 40) INFO:root:Updating 'age' to 40
>>> vars(mary) # The actual data is in a private attribute
{'name': 'Mary M', '_age': 30}
>>> vars(dave)
{'name': 'David D', '_age': 40} | = Person('Mary M', 30) # The initial age update is logged INFO:root:Updating 'age' to 30 >>> dave = Person('David D', 40) INFO:root:Updating 'age' to 40
>>> vars(mary) # The actual data is in a private attribute
{'name': 'Mary M', '_age': 30}
>>> vars(dave)
{'name': 'David D', '_age': 40} | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
32963a0f-ccf3-4faf-8906-1c9781c862ed | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,476 | supabase-export-v2 | 619b2da43c0bcdbb | .. doctest:: :hide:
>>> class ClassWithGetAttr:
... x = 123
... def __getattr__(self, attr):
... return attr.upper()
... >>> cw = ClassWithGetAttr()
>>> cw.y = 456
>>> getattr_hook(cw, 'x')
123
>>> getattr_hook(cw, 'y')
456
>>> getattr_hook(cw, 'z')
'Z' | trusted_official_docs | CPython Docs | .. doctest:: :hide:
>>> class ClassWithGetAttr:
... x = 123
... def __getattr__(self, attr):
... return attr.upper()
... >>> cw = ClassWithGetAttr()
>>> cw.y = 456
>>> getattr_hook(cw, 'x')
123
>>> getattr_hook(cw, 'y')
456
>>> getattr_hook(cw, 'z')
'Z' | .. doctest:: :hide:
>>> class ClassWithGetAttr:
... x = 123
... def __getattr__(self, attr):
... return attr.upper()
... >>> cw = ClassWithGetAttr()
>>> cw.y = 456
>>> getattr_hook(cw, 'x')
123
>>> getattr_hook(cw, 'y')
456
>>> getattr_hook(cw, 'z')
'Z' | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
33726627-5f4b-44ef-aa03-ab595d3837ac | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,601 | supabase-export-v2 | 619e8aa5b8a2c847 | of a direct lookup into ``object.__getattribute__(c, "f")`` or ``object.__getattribute__(C, "f")``. As a result, the function becomes identically accessible from either an object or a class.
Good candidates for static methods are methods that do not reference the
``self`` variable. | trusted_official_docs | CPython Docs | of a direct lookup into ``object.__getattribute__(c, "f")`` or ``object.__getattribute__(C, "f")``. As a result, the function becomes identically accessible from either an object or a class.
Good candidates for static methods are methods that do not reference the
``self`` variable. | of a direct lookup into ``object.__getattribute__(c, "f")`` or ``object.__getattribute__(C, "f")``. As a result, the function becomes identically accessible from either an object or a class.
Good candidates for static methods are methods that do not reference the
``self`` variable. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
37508087-1726-4148-ae89-0e184ef01ebb | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,673 | supabase-export-v2 | 349c8e66dbf32cc5 | >>> CP().pi Traceback (most recent call last): ... TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property.
It is not possible to create an exact drop-in pure Python version of
``__slots__`` because it requires direct access to C structures and control
over object memory allocation. However, we can b... | trusted_official_docs | CPython Docs | >>> CP().pi Traceback (most recent call last): ... TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property.
It is not possible to create an exact drop-in pure Python version of
``__slots__`` because it requires direct access to C structures and control
over object memory allocation. However, we can b... | >>> CP().pi Traceback (most recent call last): ... TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property.
It is not possible to create an exact drop-in pure Python version of
``__slots__`` because it requires direct access to C structures and control
over object memory allocation. However, we can b... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
387c556a-30ae-41ec-95e2-470c4795fc09 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,403 | supabase-export-v2 | f01be89fffee0eec | def __init__(self, minvalue=None, maxvalue=None): self.minvalue = minvalue self.maxvalue = maxvalue
def validate(self, value):
if not isinstance(value, (int, float)):
raise TypeError(f'Expected {value!r} to be an int or float')
if self.minvalue is not None and value < self.minvalue:
raise ValueError(
f'Expected {v... | trusted_official_docs | CPython Docs | def __init__(self, minvalue=None, maxvalue=None): self.minvalue = minvalue self.maxvalue = maxvalue
def validate(self, value):
if not isinstance(value, (int, float)):
raise TypeError(f'Expected {value!r} to be an int or float')
if self.minvalue is not None and value < self.minvalue:
raise ValueError(
f'Expected {v... | def __init__(self, minvalue=None, maxvalue=None): self.minvalue = minvalue self.maxvalue = maxvalue
def validate(self, value):
if not isinstance(value, (int, float)):
raise TypeError(f'Expected {value!r} to be an int or float')
if self.minvalue is not None and value < self.minvalue:
raise ValueError(
f'Expected {v... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
433555ba-7de5-44ce-aa24-087af2967bed | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,346 | supabase-export-v2 | f18d57c9cebdb46a | >>> vars(mary) # The actual data is in a private attribute {'name': 'Mary M', '_age': 30} >>> vars(dave) {'name': 'David D', '_age': 40}
>>> mary.age # Access the data and log the lookup
INFO:root:Accessing 'age' giving 30
30
>>> mary.birthday() # Updates are logged as well
INFO:root:Accessing 'age' giving 30
INFO... | trusted_official_docs | CPython Docs | >>> vars(mary) # The actual data is in a private attribute {'name': 'Mary M', '_age': 30} >>> vars(dave) {'name': 'David D', '_age': 40}
>>> mary.age # Access the data and log the lookup
INFO:root:Accessing 'age' giving 30
30
>>> mary.birthday() # Updates are logged as well
INFO:root:Accessing 'age' giving 30
INFO... | >>> vars(mary) # The actual data is in a private attribute {'name': 'Mary M', '_age': 30} >>> vars(dave) {'name': 'David D', '_age': 40}
>>> mary.age # Access the data and log the lookup
INFO:root:Accessing 'age' giving 30
30
>>> mary.birthday() # Updates are logged as well
INFO:root:Accessing 'age' giving 30
INFO... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
43aaedbd-7494-4899-b310-75f6ec495125 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,351 | supabase-export-v2 | 10f8fc5784ae10cf | When a class uses descriptors, it can inform each descriptor about which variable name was used.
In this example, the :class:`!Person` class has two descriptor instances,
*name* and *age*. When the :class:`!Person` class is defined, it makes a
callback to :meth:`~object.__set_name__` in *LoggedAccess* so that the field... | trusted_official_docs | CPython Docs | When a class uses descriptors, it can inform each descriptor about which variable name was used.
In this example, the :class:`!Person` class has two descriptor instances,
*name* and *age*. When the :class:`!Person` class is defined, it makes a
callback to :meth:`~object.__set_name__` in *LoggedAccess* so that the field... | When a class uses descriptors, it can inform each descriptor about which variable name was used.
In this example, the :class:`!Person` class has two descriptor instances,
*name* and *age*. When the :class:`!Person` class is defined, it makes a
callback to :meth:`~object.__set_name__` in *LoggedAccess* so that the field... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
44523e06-e867-4413-8cd5-833f13d044ee | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,480 | supabase-export-v2 | a011088f4b0dfe77 | :meth:`!type.__getattribute__`. The steps are similar to those for :meth:`!object.__getattribute__` but the instance dictionary lookup is replaced by a search through the class's :term:`method resolution order`.
If a descriptor is found, it is invoked with ``desc.__get__(None, A)``. | trusted_official_docs | CPython Docs | :meth:`!type.__getattribute__`. The steps are similar to those for :meth:`!object.__getattribute__` but the instance dictionary lookup is replaced by a search through the class's :term:`method resolution order`.
If a descriptor is found, it is invoked with ``desc.__get__(None, A)``. | :meth:`!type.__getattribute__`. The steps are similar to those for :meth:`!object.__getattribute__` but the instance dictionary lookup is replaced by a search through the class's :term:`method resolution order`.
If a descriptor is found, it is invoked with ``desc.__get__(None, A)``. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
47474221-7ccc-4532-976d-7634670b4b5d | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,598 | supabase-export-v2 | 03027635379e4819 | This chart summarizes the binding and its two most useful variants:
+-----------------+----------------------+------------------+
| Transformation | Called from an | Called from a |
| | object | class |
+=================+======================+==================+
| function | f(obj, \*args) | f(\*args) |
+-------... | trusted_official_docs | CPython Docs | This chart summarizes the binding and its two most useful variants:
+-----------------+----------------------+------------------+
| Transformation | Called from an | Called from a |
| | object | class |
+=================+======================+==================+
| function | f(obj, \*args) | f(\*args) |
+-------... | This chart summarizes the binding and its two most useful variants:
+-----------------+----------------------+------------------+
| Transformation | Called from an | Called from a |
| | object | class |
+=================+======================+==================+
| function | f(obj, \*args) | f(\*args) |
+-------... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
478e6612-6735-4152-abef-1408afc3f57d | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,539 | supabase-export-v2 | 86d5c8e7b88d158d | doc=None): self.fget = fget self.fset = fset self.fdel = fdel if doc is None and fget is not None: doc = fget.__doc__ self.__doc__ = doc
def __set_name__(self, owner, name):
self.__name__ = name | trusted_official_docs | CPython Docs | doc=None): self.fget = fget self.fset = fset self.fdel = fdel if doc is None and fget is not None: doc = fget.__doc__ self.__doc__ = doc
def __set_name__(self, owner, name):
self.__name__ = name | doc=None): self.fget = fget self.fset = fset self.fdel = fdel if doc is None and fget is not None: doc = fget.__doc__ self.__doc__ = doc
def __set_name__(self, owner, name):
self.__name__ = name | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
47c1c877-71d0-449b-adda-f80968e09e59 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,688 | supabase-export-v2 | e0c12d8dd8531197 | def __new__(cls, *args, **kwargs): 'Emulate object_new() in Objects/typeobject.c' inst = super().__new__(cls) if hasattr(cls, 'slot_names'): empty_slots = [null] * len(cls.slot_names) object.__setattr__(inst, '_slotvalues', empty_slots) return inst
def __setattr__(self, name, value):
'Emulate _PyObject_GenericSetAttrW... | trusted_official_docs | CPython Docs | def __new__(cls, *args, **kwargs): 'Emulate object_new() in Objects/typeobject.c' inst = super().__new__(cls) if hasattr(cls, 'slot_names'): empty_slots = [null] * len(cls.slot_names) object.__setattr__(inst, '_slotvalues', empty_slots) return inst
def __setattr__(self, name, value):
'Emulate _PyObject_GenericSetAttrW... | def __new__(cls, *args, **kwargs): 'Emulate object_new() in Objects/typeobject.c' inst = super().__new__(cls) if hasattr(cls, 'slot_names'): empty_slots = [null] * len(cls.slot_names) object.__setattr__(inst, '_slotvalues', empty_slots) return inst
def __setattr__(self, name, value):
'Emulate _PyObject_GenericSetAttrW... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
48c2e4f4-37e2-4683-80d3-815de1cbe62b | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,646 | supabase-export-v2 | 6c9ddad2782a1021 | # Verify that T uses our emulation >>> type(vars(T)['cm']).__name__ 'ClassMethod'
# Verify that update_wrapper() correctly copied attributes
>>> T.cm.__name__
'cm'
>>> T.cm.__qualname__
'T.cm'
>>> T.cm.__doc__
'Class method that returns a tuple'
>>> T.cm.__annotations__
{'x': <class 'int'>, 'y': <class 'str'>, ... | trusted_official_docs | CPython Docs | # Verify that T uses our emulation >>> type(vars(T)['cm']).__name__ 'ClassMethod'
# Verify that update_wrapper() correctly copied attributes
>>> T.cm.__name__
'cm'
>>> T.cm.__qualname__
'T.cm'
>>> T.cm.__doc__
'Class method that returns a tuple'
>>> T.cm.__annotations__
{'x': <class 'int'>, 'y': <class 'str'>, ... | # Verify that T uses our emulation >>> type(vars(T)['cm']).__name__ 'ClassMethod'
# Verify that update_wrapper() correctly copied attributes
>>> T.cm.__name__
'cm'
>>> T.cm.__qualname__
'T.cm'
>>> T.cm.__doc__
'Class method that returns a tuple'
>>> T.cm.__annotations__
{'x': <class 'int'>, 'y': <class 'str'>, ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
493e1d18-9f20-4776-a230-432f909059a8 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,535 | supabase-export-v2 | 80de8584ec72c9c5 | >>> c.x = 2.71828 >>> c.x 2.71828 >>> del c.x >>> c.x Traceback (most recent call last): ... AttributeError: 'C' object has no attribute '_C__x'
To see how :func:`property` is implemented in terms of the descriptor protocol,
here is a pure Python equivalent that implements most of the core functionality: | trusted_official_docs | CPython Docs | >>> c.x = 2.71828 >>> c.x 2.71828 >>> del c.x >>> c.x Traceback (most recent call last): ... AttributeError: 'C' object has no attribute '_C__x'
To see how :func:`property` is implemented in terms of the descriptor protocol,
here is a pure Python equivalent that implements most of the core functionality: | >>> c.x = 2.71828 >>> c.x 2.71828 >>> del c.x >>> c.x Traceback (most recent call last): ... AttributeError: 'C' object has no attribute '_C__x'
To see how :func:`property` is implemented in terms of the descriptor protocol,
here is a pure Python equivalent that implements most of the core functionality: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
495b16c9-0202-4b90-910b-40d6b8067ecd | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,440 | supabase-export-v2 | 9322c5fc34d5acb0 | for ``obj``. If the search finds a descriptor outside of the instance :attr:`~object.__dict__`, its :meth:`~object.__get__` method is invoked according to the precedence rules listed below.
The details of invocation depend on whether ``obj`` is an object, class, or
instance of super. | trusted_official_docs | CPython Docs | for ``obj``. If the search finds a descriptor outside of the instance :attr:`~object.__dict__`, its :meth:`~object.__get__` method is invoked according to the precedence rules listed below.
The details of invocation depend on whether ``obj`` is an object, class, or
instance of super. | for ``obj``. If the search finds a descriptor outside of the instance :attr:`~object.__dict__`, its :meth:`~object.__get__` method is invoked according to the precedence rules listed below.
The details of invocation depend on whether ``obj`` is an object, class, or
instance of super. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
4aae99d3-bd2c-46de-80c4-b84a5a53e5ad | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,470 | supabase-export-v2 | 9ae3a5d9c37ad28e | 22 True >>> b.p2 == b['p2'] == 30 True >>> b.m5(200) == b['m5'](200) == 1000 True >>> b.g == b['g'] == ('getattr_hook', b, 'g') True
>>> u2 = U2()
>>> object_getattribute(u2, 'x') == u2.x == (D1, u2, U2)
True | trusted_official_docs | CPython Docs | 22 True >>> b.p2 == b['p2'] == 30 True >>> b.m5(200) == b['m5'](200) == 1000 True >>> b.g == b['g'] == ('getattr_hook', b, 'g') True
>>> u2 = U2()
>>> object_getattribute(u2, 'x') == u2.x == (D1, u2, U2)
True | 22 True >>> b.p2 == b['p2'] == 30 True >>> b.m5(200) == b['m5'](200) == 1000 True >>> b.g == b['g'] == ('getattr_hook', b, 'g') True
>>> u2 = U2()
>>> object_getattribute(u2, 'x') == u2.x == (D1, u2, U2)
True | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
4ab10009-2bfe-4bd2-b0ab-71608f4bbd65 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,690 | supabase-export-v2 | 74f11071e2b3776a | name): 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c' cls = type(self) if hasattr(cls, 'slot_names') and name not in cls.slot_names: raise AttributeError( f'{cls.__name__!r} object has no attribute {name!r}' ) super().__delattr__(name)
To use the simulation in a real class, just inherit from :class:`!Obj... | trusted_official_docs | CPython Docs | name): 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c' cls = type(self) if hasattr(cls, 'slot_names') and name not in cls.slot_names: raise AttributeError( f'{cls.__name__!r} object has no attribute {name!r}' ) super().__delattr__(name)
To use the simulation in a real class, just inherit from :class:`!Obj... | name): 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c' cls = type(self) if hasattr(cls, 'slot_names') and name not in cls.slot_names: raise AttributeError( f'{cls.__name__!r} object has no attribute {name!r}' ) super().__delattr__(name)
To use the simulation in a real class, just inherit from :class:`!Obj... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
4bf2ec7b-6370-40c3-b922-a10c455a484f | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,596 | supabase-export-v2 | 08e46be460fb8a2f | Non-data descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods.
To recap, functions have a :meth:`~object.__get__` method so that they can be converted
to a method when accessed as attributes. The non-data descriptor transforms an
``obj.f(*args)`` call into ``f(ob... | trusted_official_docs | CPython Docs | Non-data descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods.
To recap, functions have a :meth:`~object.__get__` method so that they can be converted
to a method when accessed as attributes. The non-data descriptor transforms an
``obj.f(*args)`` call into ``f(ob... | Non-data descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods.
To recap, functions have a :meth:`~object.__get__` method so that they can be converted
to a method when accessed as attributes. The non-data descriptor transforms an
``obj.f(*args)`` call into ``f(ob... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
4e8ee8e4-e76d-4acd-b263-043ff0f79fb9 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,677 | supabase-export-v2 | 5620aae381231743 | in Objects/descrobject.c' # Also see PyMember_GetOne() in Python/structmember.c if obj is None: return self value = obj._slotvalues[self.offset] if value is null: raise AttributeError(self.name) return value
def __set__(self, obj, value):
'Emulate member_set() in Objects/descrobject.c'
obj._slotvalues[self.offset] = ... | trusted_official_docs | CPython Docs | in Objects/descrobject.c' # Also see PyMember_GetOne() in Python/structmember.c if obj is None: return self value = obj._slotvalues[self.offset] if value is null: raise AttributeError(self.name) return value
def __set__(self, obj, value):
'Emulate member_set() in Objects/descrobject.c'
obj._slotvalues[self.offset] = ... | in Objects/descrobject.c' # Also see PyMember_GetOne() in Python/structmember.c if obj is None: return self value = obj._slotvalues[self.offset] if value is null: raise AttributeError(self.name) return value
def __set__(self, obj, value):
'Emulate member_set() in Objects/descrobject.c'
obj._slotvalues[self.offset] = ... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5267b9ba-c8ab-499d-bcaa-7a92d9fc9e6b | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,369 | supabase-export-v2 | c298cb5db4aed48c | .. doctest::
>>> pete = Person('Peter P', 10)
INFO:root:Updating 'name' to 'Peter P'
INFO:root:Updating 'age' to 10
>>> kate = Person('Catherine C', 20)
INFO:root:Updating 'name' to 'Catherine C'
INFO:root:Updating 'age' to 20 | trusted_official_docs | CPython Docs | .. doctest::
>>> pete = Person('Peter P', 10)
INFO:root:Updating 'name' to 'Peter P'
INFO:root:Updating 'age' to 10
>>> kate = Person('Catherine C', 20)
INFO:root:Updating 'name' to 'Catherine C'
INFO:root:Updating 'age' to 20 | .. doctest::
>>> pete = Person('Peter P', 10)
INFO:root:Updating 'name' to 'Peter P'
INFO:root:Updating 'age' to 10
>>> kate = Person('Catherine C', 20)
INFO:root:Updating 'name' to 'Catherine C'
INFO:root:Updating 'age' to 20 | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5335e52c-cbcc-48db-8817-e2040c6a11d3 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,301 | supabase-export-v2 | e61b47b21389c52a | third section provides a more technical tutorial that goes into the detailed mechanics of how descriptors work. Most people don't need this level of detail.
4) The last section has pure Python equivalents for built-in descriptors that
are written in C. Read this if you're curious about how functions turn
into bound m... | trusted_official_docs | CPython Docs | third section provides a more technical tutorial that goes into the detailed mechanics of how descriptors work. Most people don't need this level of detail.
4) The last section has pure Python equivalents for built-in descriptors that
are written in C. Read this if you're curious about how functions turn
into bound m... | third section provides a more technical tutorial that goes into the detailed mechanics of how descriptors work. Most people don't need this level of detail.
4) The last section has pure Python equivalents for built-in descriptors that
are written in C. Read this if you're curious about how functions turn
into bound m... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
542bdc47-716d-4d70-b9c8-528602e80b1f | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,574 | supabase-export-v2 | d396ed103b983023 | def __get__(self, obj, objtype=None): "Emulate method_descr_get() in Objects/classobject.c" return self
To support automatic creation of methods, functions include the
:meth:`~object.__get__` method for binding methods during attribute access. This
means that functions are non-data descriptors that return bound methods... | trusted_official_docs | CPython Docs | def __get__(self, obj, objtype=None): "Emulate method_descr_get() in Objects/classobject.c" return self
To support automatic creation of methods, functions include the
:meth:`~object.__get__` method for binding methods during attribute access. This
means that functions are non-data descriptors that return bound methods... | def __get__(self, obj, objtype=None): "Emulate method_descr_get() in Objects/classobject.c" return self
To support automatic creation of methods, functions include the
:meth:`~object.__get__` method for binding methods during attribute access. This
means that functions are non-data descriptors that return bound methods... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
575ad29c-9d52-4b48-baf9-4db97932a039 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,493 | supabase-export-v2 | 890765e4ea714d87 | to :meth:`~object.__get__`. The first includes the instance and may include the class. The second puts in ``None`` for the instance and always includes the class.
* Data descriptors always override instance dictionaries. | trusted_official_docs | CPython Docs | to :meth:`~object.__get__`. The first includes the instance and may include the class. The second puts in ``None`` for the instance and always includes the class.
* Data descriptors always override instance dictionaries. | to :meth:`~object.__get__`. The first includes the instance and may include the class. The second puts in ``None`` for the instance and always includes the class.
* Data descriptors always override instance dictionaries. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5a1735d8-9a25-42a3-9124-59c833bf1dc2 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,479 | supabase-export-v2 | 7e24ac7f75bd8af2 | Invocation from a class -----------------------
The logic for a dotted lookup such as ``A.x`` is in
:meth:`!type.__getattribute__`. The steps are similar to those for
:meth:`!object.__getattribute__` but the instance dictionary lookup is replaced
by a search through the class's :term:`method resolution order`. | trusted_official_docs | CPython Docs | Invocation from a class -----------------------
The logic for a dotted lookup such as ``A.x`` is in
:meth:`!type.__getattribute__`. The steps are similar to those for
:meth:`!object.__getattribute__` but the instance dictionary lookup is replaced
by a search through the class's :term:`method resolution order`. | Invocation from a class -----------------------
The logic for a dotted lookup such as ``A.x`` is in
:meth:`!type.__getattribute__`. The steps are similar to those for
:meth:`!object.__getattribute__` but the instance dictionary lookup is replaced
by a search through the class's :term:`method resolution order`. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5ccb69e2-0ed8-47b6-a7dd-12ce1e6bf88e | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,665 | supabase-export-v2 | ce4429f6a4054b5c | with ``__slots__`` and 152 bytes without. This `flyweight design pattern <https://en.wikipedia.org/wiki/Flyweight_pattern>`_ likely only matters when a large number of instances are going to be created.
4. Improves speed. Reading instance variables is 35% faster with
``__slots__`` (as measured with Python 3.10 on an Ap... | trusted_official_docs | CPython Docs | with ``__slots__`` and 152 bytes without. This `flyweight design pattern <https://en.wikipedia.org/wiki/Flyweight_pattern>`_ likely only matters when a large number of instances are going to be created.
4. Improves speed. Reading instance variables is 35% faster with
``__slots__`` (as measured with Python 3.10 on an Ap... | with ``__slots__`` and 152 bytes without. This `flyweight design pattern <https://en.wikipedia.org/wiki/Flyweight_pattern>`_ likely only matters when a large number of instances are going to be created.
4. Improves speed. Reading instance variables is 35% faster with
``__slots__`` (as measured with Python 3.10 on an Ap... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5dc131e6-e3ac-4f11-bf2f-9b1703f06521 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,650 | supabase-export-v2 | 45ce4ca2d394bc6d | Member objects and __slots__ ----------------------------
When a class defines ``__slots__``, it replaces instance dictionaries with a
fixed-length array of slot values. From a user point of view that has
several effects: | trusted_official_docs | CPython Docs | Member objects and __slots__ ----------------------------
When a class defines ``__slots__``, it replaces instance dictionaries with a
fixed-length array of slot values. From a user point of view that has
several effects: | Member objects and __slots__ ----------------------------
When a class defines ``__slots__``, it replaces instance dictionaries with a
fixed-length array of slot values. From a user point of view that has
several effects: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
5fdb1168-1c61-4fe7-89f3-7d877e3348e8 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,602 | supabase-export-v2 | 46c5a2466fa48d11 | Good candidates for static methods are methods that do not reference the ``self`` variable.
For instance, a statistics package may include a container class for
experimental data. The class provides normal methods for computing the average,
mean, median, and other descriptive statistics that depend on the data. However... | trusted_official_docs | CPython Docs | Good candidates for static methods are methods that do not reference the ``self`` variable.
For instance, a statistics package may include a container class for
experimental data. The class provides normal methods for computing the average,
mean, median, and other descriptive statistics that depend on the data. However... | Good candidates for static methods are methods that do not reference the ``self`` variable.
For instance, a statistics package may include a container class for
experimental data. The class provides normal methods for computing the average,
mean, median, and other descriptive statistics that depend on the data. However... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
64f4c056-2d83-4963-923b-a42343ee52d2 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,417 | supabase-export-v2 | fdf6a1cbc0a1181e | >>> Component('WIDGET', 'metal', -5) # Blocked: -5 is negative Traceback (most recent call last): ... ValueError: Expected -5 to be at least 0
>>> Component('WIDGET', 'metal', 'V') # Blocked: 'V' isn't a number
Traceback (most recent call last):
... TypeError: Expected 'V' to be an int or float | trusted_official_docs | CPython Docs | >>> Component('WIDGET', 'metal', -5) # Blocked: -5 is negative Traceback (most recent call last): ... ValueError: Expected -5 to be at least 0
>>> Component('WIDGET', 'metal', 'V') # Blocked: 'V' isn't a number
Traceback (most recent call last):
... TypeError: Expected 'V' to be an int or float | >>> Component('WIDGET', 'metal', -5) # Blocked: -5 is negative Traceback (most recent call last): ... ValueError: Expected -5 to be at least 0
>>> Component('WIDGET', 'metal', 'V') # Blocked: 'V' isn't a number
Traceback (most recent call last):
... TypeError: Expected 'V' to be an int or float | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
688ae9b6-9596-46ed-a925-bf7d6261594e | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,484 | supabase-export-v2 | d01b8d40a1518501 | The logic for super's dotted lookup is in the :meth:`~object.__getattribute__` method for object returned by :func:`super`.
A dotted lookup such as ``super(A, obj).m`` searches ``obj.__class__.__mro__``
for the base class ``B`` immediately following ``A`` and then returns
``B.__dict__['m'].__get__(obj, A)``. If not a d... | trusted_official_docs | CPython Docs | The logic for super's dotted lookup is in the :meth:`~object.__getattribute__` method for object returned by :func:`super`.
A dotted lookup such as ``super(A, obj).m`` searches ``obj.__class__.__mro__``
for the base class ``B`` immediately following ``A`` and then returns
``B.__dict__['m'].__get__(obj, A)``. If not a d... | The logic for super's dotted lookup is in the :meth:`~object.__getattribute__` method for object returned by :func:`super`.
A dotted lookup such as ``super(A, obj).m`` searches ``obj.__class__.__mro__``
for the base class ``B`` immediately following ``A`` and then returns
``B.__dict__['m'].__get__(obj, A)``. If not a d... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6bb4c69a-5f14-4b63-b4b1-a7adf3b01640 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,299 | supabase-export-v2 | d17ffa44394b61a9 | 1) The "primer" gives a basic overview, moving gently from simple examples, adding one feature at a time. Start here if you're new to descriptors.
2) The second section shows a complete, practical descriptor example. If you
already know the basics, start there. | trusted_official_docs | CPython Docs | 1) The "primer" gives a basic overview, moving gently from simple examples, adding one feature at a time. Start here if you're new to descriptors.
2) The second section shows a complete, practical descriptor example. If you
already know the basics, start there. | 1) The "primer" gives a basic overview, moving gently from simple examples, adding one feature at a time. Start here if you're new to descriptors.
2) The second section shows a complete, practical descriptor example. If you
already know the basics, start there. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6bee744a-d4ca-40d0-99c7-7f615c3e9dff | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,433 | supabase-export-v2 | debf0db76e010b42 | it. Define any of these methods and an object is considered a descriptor and can override default behavior upon being looked up as an attribute.
If an object defines :meth:`~object.__set__` or :meth:`~object.__delete__`, it is considered
a data descriptor. Descriptors that only define :meth:`~object.__get__` are called... | trusted_official_docs | CPython Docs | it. Define any of these methods and an object is considered a descriptor and can override default behavior upon being looked up as an attribute.
If an object defines :meth:`~object.__set__` or :meth:`~object.__delete__`, it is considered
a data descriptor. Descriptors that only define :meth:`~object.__get__` are called... | it. Define any of these methods and an object is considered a descriptor and can override default behavior upon being looked up as an attribute.
If an object defines :meth:`~object.__set__` or :meth:`~object.__delete__`, it is considered
a data descriptor. Descriptors that only define :meth:`~object.__get__` are called... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6c703533-89c3-4ce2-8781-c83400d2595b | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,538 | supabase-export-v2 | a11ba4f341852de5 | class Property: "Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc | trusted_official_docs | CPython Docs | class Property: "Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc | class Property: "Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6c8e60d2-725b-4117-a513-44ead33a5b77 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,443 | supabase-export-v2 | 4fde0771fd374333 | of namespaces giving data descriptors the highest priority, followed by instance variables, then non-data descriptors, then class variables, and lastly :meth:`~object.__getattr__` if it is provided.
If a descriptor is found for ``a.x``, then it is invoked with:
``desc.__get__(a, type(a))``. | trusted_official_docs | CPython Docs | of namespaces giving data descriptors the highest priority, followed by instance variables, then non-data descriptors, then class variables, and lastly :meth:`~object.__getattr__` if it is provided.
If a descriptor is found for ``a.x``, then it is invoked with:
``desc.__get__(a, type(a))``. | of namespaces giving data descriptors the highest priority, followed by instance variables, then non-data descriptors, then class variables, and lastly :meth:`~object.__getattr__` if it is provided.
If a descriptor is found for ``a.x``, then it is invoked with:
``desc.__get__(a, type(a))``. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6d56ffbd-f3ae-47bb-8265-694578cfacb7 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,571 | supabase-export-v2 | d25aa33742f53934 | def __call__(self, *args, **kwargs): func = self.__func__ obj = self.__self__ return func(obj, *args, **kwargs)
def __getattribute__(self, name):
"Emulate method_getset() in Objects/classobject.c"
if name == '__doc__':
return self.__func__.__doc__
return object.__getattribute__(self, name) | trusted_official_docs | CPython Docs | def __call__(self, *args, **kwargs): func = self.__func__ obj = self.__self__ return func(obj, *args, **kwargs)
def __getattribute__(self, name):
"Emulate method_getset() in Objects/classobject.c"
if name == '__doc__':
return self.__func__.__doc__
return object.__getattribute__(self, name) | def __call__(self, *args, **kwargs): func = self.__func__ obj = self.__self__ return func(obj, *args, **kwargs)
def __getattribute__(self, name):
"Emulate method_getset() in Objects/classobject.c"
if name == '__doc__':
return self.__func__.__doc__
return object.__getattribute__(self, name) | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6d8988be-cc76-4ba9-a875-152a877617d9 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,683 | supabase-export-v2 | e17daf8b822499fb | class Type(type): 'Simulate how the type metaclass adds member objects for slots'
def __new__(mcls, clsname, bases, mapping, **kwargs):
'Emulate type_new() in Objects/typeobject.c'
# type_new() calls PyTypeReady() which calls add_methods()
slot_names = mapping.get('slot_names', [])
for offset, name in enumerate(slo... | trusted_official_docs | CPython Docs | class Type(type): 'Simulate how the type metaclass adds member objects for slots'
def __new__(mcls, clsname, bases, mapping, **kwargs):
'Emulate type_new() in Objects/typeobject.c'
# type_new() calls PyTypeReady() which calls add_methods()
slot_names = mapping.get('slot_names', [])
for offset, name in enumerate(slo... | class Type(type): 'Simulate how the type metaclass adds member objects for slots'
def __new__(mcls, clsname, bases, mapping, **kwargs):
'Emulate type_new() in Objects/typeobject.c'
# type_new() calls PyTypeReady() which calls add_methods()
slot_names = mapping.get('slot_names', [])
for offset, name in enumerate(slo... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6d91fc5c-d040-42c4-ba53-aea73ff2fd2f | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,485 | supabase-export-v2 | fc0a813b19095832 | ``super(A, obj).m`` searches ``obj.__class__.__mro__`` for the base class ``B`` immediately following ``A`` and then returns ``B.__dict__['m'].__get__(obj, A)``. If not a descriptor, ``m`` is returned unchanged.
The full C implementation can be found in :c:func:`!super_getattro` in
:source:`Objects/typeobject.c`. A pur... | trusted_official_docs | CPython Docs | ``super(A, obj).m`` searches ``obj.__class__.__mro__`` for the base class ``B`` immediately following ``A`` and then returns ``B.__dict__['m'].__get__(obj, A)``. If not a descriptor, ``m`` is returned unchanged.
The full C implementation can be found in :c:func:`!super_getattro` in
:source:`Objects/typeobject.c`. A pur... | ``super(A, obj).m`` searches ``obj.__class__.__mro__`` for the base class ``B`` immediately following ``A`` and then returns ``B.__dict__['m'].__get__(obj, A)``. If not a descriptor, ``m`` is returned unchanged.
The full C implementation can be found in :c:func:`!super_getattro` in
:source:`Objects/typeobject.c`. A pur... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
6f620896-76c0-4a26-a5f4-ac3ad31ca802 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,326 | supabase-export-v2 | 70f3c690c37b7d13 | An interactive session shows that the lookup is dynamic — it computes different, updated answers each time::
>>> s = Directory('songs')
>>> g = Directory('games')
>>> s.size # The songs directory has twenty files
20
>>> g.size # The games directory has three files
3
>>> os.remove('games/chess') # Delete a game
>... | trusted_official_docs | CPython Docs | An interactive session shows that the lookup is dynamic — it computes different, updated answers each time::
>>> s = Directory('songs')
>>> g = Directory('games')
>>> s.size # The songs directory has twenty files
20
>>> g.size # The games directory has three files
3
>>> os.remove('games/chess') # Delete a game
>... | An interactive session shows that the lookup is dynamic — it computes different, updated answers each time::
>>> s = Directory('songs')
>>> g = Directory('games')
>>> s.size # The songs directory has twenty files
20
>>> g.size # The games directory has three files
3
>>> os.remove('games/chess') # Delete a game
>... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
703c2e5b-da41-4dfd-8b4a-42b9b3b8247c | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,656 | supabase-export-v2 | 4472e8897840559d | >>> auto = Vehicle() >>> auto.id_nubmer = 'VYE483814LQEX' Traceback (most recent call last): ... AttributeError: 'Vehicle' object has no attribute 'id_nubmer'
2. Helps create immutable objects where descriptors manage access to private
attributes stored in ``__slots__``: | trusted_official_docs | CPython Docs | >>> auto = Vehicle() >>> auto.id_nubmer = 'VYE483814LQEX' Traceback (most recent call last): ... AttributeError: 'Vehicle' object has no attribute 'id_nubmer'
2. Helps create immutable objects where descriptors manage access to private
attributes stored in ``__slots__``: | >>> auto = Vehicle() >>> auto.id_nubmer = 'VYE483814LQEX' Traceback (most recent call last): ... AttributeError: 'Vehicle' object has no attribute 'id_nubmer'
2. Helps create immutable objects where descriptors manage access to private
attributes stored in ``__slots__``: | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
74818281-b917-4b36-9e4d-9bbad3c24b90 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,589 | supabase-export-v2 | f09a8bb3d5b1dbeb | The interesting behavior occurs during dotted access from an instance. The dotted lookup calls :meth:`~object.__get__` which returns a bound method object::
>>> d = D()
>>> d.f
<bound method D.f of <__main__.D object at 0x00B18C90>> | trusted_official_docs | CPython Docs | The interesting behavior occurs during dotted access from an instance. The dotted lookup calls :meth:`~object.__get__` which returns a bound method object::
>>> d = D()
>>> d.f
<bound method D.f of <__main__.D object at 0x00B18C90>> | The interesting behavior occurs during dotted access from an instance. The dotted lookup calls :meth:`~object.__get__` which returns a bound method object::
>>> d = D()
>>> d.f
<bound method D.f of <__main__.D object at 0x00B18C90>> | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
772ac38d-a9a9-429b-9c82-fd7f3ad76142 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,648 | supabase-export-v2 | 4b32dbf83fbd9548 | Verify that __wrapped__ was added and works correctly >>> f = vars(T)['cm'].__wrapped__ >>> type(f).__name__ 'function' >>> f.__name__ 'cm' >>> f(T, 11, 22) ('T', 11, 22)
The :func:`functools.update_wrapper` call in ``ClassMethod`` adds a
``__wrapped__`` attribute that refers to the underlying function. Also
it carries... | trusted_official_docs | CPython Docs | Verify that __wrapped__ was added and works correctly >>> f = vars(T)['cm'].__wrapped__ >>> type(f).__name__ 'function' >>> f.__name__ 'cm' >>> f(T, 11, 22) ('T', 11, 22)
The :func:`functools.update_wrapper` call in ``ClassMethod`` adds a
``__wrapped__`` attribute that refers to the underlying function. Also
it carries... | Verify that __wrapped__ was added and works correctly >>> f = vars(T)['cm'].__wrapped__ >>> type(f).__name__ 'function' >>> f.__name__ 'cm' >>> f(T, 11, 22) ('T', 11, 22)
The :func:`functools.update_wrapper` call in ``ClassMethod`` adds a
``__wrapped__`` attribute that refers to the underlying function. Also
it carries... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
78668b20-6f09-44d2-ae4f-263e9ff5dd0f | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,529 | supabase-export-v2 | 29e1fd17754d8a85 | Calling :func:`property` is a succinct way of building a data descriptor that triggers a function call upon access to an attribute. Its signature is::
property(fget=None, fset=None, fdel=None, doc=None) -> property | trusted_official_docs | CPython Docs | Calling :func:`property` is a succinct way of building a data descriptor that triggers a function call upon access to an attribute. Its signature is::
property(fget=None, fset=None, fdel=None, doc=None) -> property | Calling :func:`property` is a succinct way of building a data descriptor that triggers a function call upon access to an attribute. Its signature is::
property(fget=None, fset=None, fdel=None, doc=None) -> property | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
79a7c206-b7b9-42d3-84d9-1af213ad675e | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,442 | supabase-export-v2 | 6414728a6ac8bd15 | Invocation from an instance ---------------------------
Instance lookup scans through a chain of namespaces giving data descriptors
the highest priority, followed by instance variables, then non-data
descriptors, then class variables, and lastly :meth:`~object.__getattr__` if it is
provided. | trusted_official_docs | CPython Docs | Invocation from an instance ---------------------------
Instance lookup scans through a chain of namespaces giving data descriptors
the highest priority, followed by instance variables, then non-data
descriptors, then class variables, and lastly :meth:`~object.__getattr__` if it is
provided. | Invocation from an instance ---------------------------
Instance lookup scans through a chain of namespaces giving data descriptors
the highest priority, followed by instance variables, then non-data
descriptors, then class variables, and lastly :meth:`~object.__getattr__` if it is
provided. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
7a53e1f2-d339-4dfd-81e3-aa40a7ffb4f1 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,696 | supabase-export-v2 | 88b821e0def9bae6 | At this point, the metaclass has loaded member objects for *x* and *y*::
>>> from pprint import pp
>>> pp(dict(vars(H)))
{'__module__': '__main__',
'__doc__': 'Instance variables stored in slots',
'slot_names': ['x', 'y'],
'__init__': <function H.__init__ at 0x7fb5d302f9d0>,
'x': <Member 'x' of 'H'>,
'y': <Membe... | trusted_official_docs | CPython Docs | At this point, the metaclass has loaded member objects for *x* and *y*::
>>> from pprint import pp
>>> pp(dict(vars(H)))
{'__module__': '__main__',
'__doc__': 'Instance variables stored in slots',
'slot_names': ['x', 'y'],
'__init__': <function H.__init__ at 0x7fb5d302f9d0>,
'x': <Member 'x' of 'H'>,
'y': <Membe... | At this point, the metaclass has loaded member objects for *x* and *y*::
>>> from pprint import pp
>>> pp(dict(vars(H)))
{'__module__': '__main__',
'__doc__': 'Instance variables stored in slots',
'slot_names': ['x', 'y'],
'__init__': <function H.__init__ at 0x7fb5d302f9d0>,
'x': <Member 'x' of 'H'>,
'y': <Membe... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
7b496f6d-a589-47ce-9bac-efd3f827276f | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,469 | supabase-export-v2 | 7d9d3730a2b03696 | 30 True >>> a.m5(100) == a.m5(100) == 500 True >>> a.m7 == a['m7'] == '_m7' True >>> a.g == a['g'] == ('getattr_hook', a, 'g') True
>>> b = DualOperatorWithSlots(22)
>>> b.x == b['x'] == 15
True
>>> b.z == b['z'] == 22
True
>>> b.p2 == b['p2'] == 30
True
>>> b.m5(200) == b['m5'](200) == 1000
True
>>> b.g == b[... | trusted_official_docs | CPython Docs | 30 True >>> a.m5(100) == a.m5(100) == 500 True >>> a.m7 == a['m7'] == '_m7' True >>> a.g == a['g'] == ('getattr_hook', a, 'g') True
>>> b = DualOperatorWithSlots(22)
>>> b.x == b['x'] == 15
True
>>> b.z == b['z'] == 22
True
>>> b.p2 == b['p2'] == 30
True
>>> b.m5(200) == b['m5'](200) == 1000
True
>>> b.g == b[... | 30 True >>> a.m5(100) == a.m5(100) == 500 True >>> a.m7 == a['m7'] == '_m7' True >>> a.g == a['g'] == ('getattr_hook', a, 'g') True
>>> b = DualOperatorWithSlots(22)
>>> b.x == b['x'] == 15
True
>>> b.z == b['z'] == 22
True
>>> b.p2 == b['p2'] == 30
True
>>> b.m5(200) == b['m5'](200) == 1000
True
>>> b.g == b[... | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
7efb4bd9-ed90-429a-b64f-5afe4d3da881 | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,316 | supabase-export-v2 | 8db38b145332a62f | Note that the value ``10`` is not stored in either the class dictionary or the instance dictionary. Instead, the value ``10`` is computed on demand.
This example shows how a simple descriptor works, but it isn't very useful. For retrieving constants, normal attribute lookup would be better. | trusted_official_docs | CPython Docs | Note that the value ``10`` is not stored in either the class dictionary or the instance dictionary. Instead, the value ``10`` is computed on demand.
This example shows how a simple descriptor works, but it isn't very useful. For retrieving constants, normal attribute lookup would be better. | Note that the value ``10`` is not stored in either the class dictionary or the instance dictionary. Instead, the value ``10`` is computed on demand.
This example shows how a simple descriptor works, but it isn't very useful. For retrieving constants, normal attribute lookup would be better. | python, official-docs, cpython, P0 | Local_Trusted_Corpus | |
7fd4f1a7-d9ed-4fd5-942a-7c921430de6f | CPython Docs | file://datasets/cpython/Doc/howto/descriptor.rst | unknown | 648a56dc-df5a-4761-a637-03ab957df2ef | 58,496 | supabase-export-v2 | 28d68c648852fcb4 | Automatic name notification ---------------------------
Sometimes it is desirable for a descriptor to know what class variable name it
was assigned to. When a new class is created, the :class:`type` metaclass
scans the dictionary of the new class. If any of the entries are descriptors
and if they define :meth:`~object.... | trusted_official_docs | CPython Docs | Automatic name notification ---------------------------
Sometimes it is desirable for a descriptor to know what class variable name it
was assigned to. When a new class is created, the :class:`type` metaclass
scans the dictionary of the new class. If any of the entries are descriptors
and if they define :meth:`~object.... | Automatic name notification ---------------------------
Sometimes it is desirable for a descriptor to know what class variable name it
was assigned to. When a new class is created, the :class:`type` metaclass
scans the dictionary of the new class. If any of the entries are descriptors
and if they define :meth:`~object.... | python, official-docs, cpython, P0 | Local_Trusted_Corpus |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.