Trăn tương lai

Bộ công cụ giáo dục AIOT Python của Future Board

Bộ công cụ giáo dục AIOT Python của Future Board ESP32 Khởi động nhanh Ổ cắm USB gốc 2. Bật công tắc 3. Đi tới hướng dẫn thiết lập Tài nguyên trên mạch Pin Lập trình Tải xuống. mèo con. cn/software kittyCode Python Kittenblock Hỗ trợ sau bán hàng Website. www. mèo con. cc Cong dong. vùng. mèo con. cn Bảo Hành Sản Phẩm Cảm ơn bạn đã mua sản phẩm của chúng tôi. Hành động này được bảo vệ kéo dài một năm kể từ…

Tiếp tục đọc “Hướng dẫn sử dụng KittenBot ESP32 Future Board AIOT Python Education Kit”

Tháng Một 15, 2022Tháng Một 18, 2022Được đăng trong KittenBottags. 2AYUR-KBK9057A, 2AYURKBK9057A, Bộ công giáo Python AIOT của Hội đồng tương lai ESP32, Bộ công giáo Python AIOT của Future Board, KBK9057A, KittenBot

GHI CHÚ. Trang này vẫn đang trong quá trình hoàn thiện.. Chúng tôi cần xem qua các chuỗi tài liệu của mình và làm cho chúng tương thích với sphinx, đồng thời tìm ra cách cải thiện định dạng bằng plugin sphinx-bootstrap-theme. Yêu cầu kéo sẽ rất được hoan nghênh

Một mô-đun mang nội dung tương đương của Python 3 mới và đã sửa đổi vào Py2. Không ảnh hưởng đến Py3

Xem tài liệu tại đây [

import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg    # on Windows only
import test.support
import html, html.parser, html.entites
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server

import _thread
import _dummy_thread
import _markupbase

from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap     # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output              # even on Py2.6
2] để biết thêm thông tin

Mô-đun này chứa các bản nhập ngược các loại dữ liệu đã thay đổi đáng kể trong quá trình chuyển đổi từ Python 2 sang Python 3

  • triển khai đối tượng byte của Python 3 [lớp con Python thuần túy của loại str 8 bit dựng sẵn của Python 2]

  • triển khai đối tượng str của Python 3 [lớp con Python thuần túy của loại unicode dựng sẵn của Python 2]

  • một cổng sau của trình lặp phạm vi từ Py3 với hỗ trợ cắt

Nó được sử dụng như sau

from __future__ import division, absolute_import, print_function
from builtins import bytes, dict, int, range, str

để mang lại ngữ nghĩa mới cho các chức năng này từ Python 3. Và sau đó, ví dụ

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function

  • Tương lai. các loại. byte mới

  • Tương lai. các loại. người mới ra lệnh

  • Tương lai. các loại. người mới

  • Tương lai. các loại. đối tượng mới

  • Tương lai. các loại. phạm vi mới

  • Tương lai. các loại. bản tin

ghi chú

import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg    # on Windows only
import test.support
import html, html.parser, html.entites
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server

import _thread
import _dummy_thread
import _markupbase

from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap     # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output              # even on Py2.6
3 là một lớp tùy chỉnh nhập ngược hành vi cắt từ Python 3 [dựa trên mô-đun
import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg    # on Windows only
import test.support
import html, html.parser, html.entites
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server

import _thread
import _dummy_thread
import _markupbase

from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap     # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output              # even on Py2.6
4 của Dan Crosta]. Xem chuỗi tài liệu mô-đun
import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg    # on Windows only
import test.support
import html, html.parser, html.entites
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server

import _thread
import _dummy_thread
import _markupbase

from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap     # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output              # even on Py2.6
5 để biết thêm chi tiết

import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg    # on Windows only
import test.support
import html, html.parser, html.entites
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server

import _thread
import _dummy_thread
import _markupbase

from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap     # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output              # even on Py2.6
6 dựa trên mô-đun
import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg    # on Windows only
import test.support
import html, html.parser, html.entites
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server

import _thread
import _dummy_thread
import _markupbase

from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap     # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output              # even on Py2.6
7 của Ryan Kelly. Xem chuỗi tài liệu mô-đun
import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg    # on Windows only
import test.support
import html, html.parser, html.entites
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server

import _thread
import _dummy_thread
import _markupbase

from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap     # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output              # even on Py2.6
8 để biết thêm chi tiết

Python 3 sửa đổi hành vi của

import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg    # on Windows only
import test.support
import html, html.parser, html.entites
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server

import _thread
import _dummy_thread
import _markupbase

from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap     # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output              # even on Py2.6
9 để sử dụng “Làm tròn ngân hàng”. xem http. // stackoverflow. com/a/10825998. Xem chuỗi tài liệu mô-đun
try:
    import queue
except ImportError:
    import Queue as queue
0 để biết thêm chi tiết

Python 3 đã tổ chức lại thư viện chuẩn [PEP 3108]. Mô-đun này hiển thị một số mô-đun thư viện chuẩn cho Python 2 dưới tên Python 3 mới của chúng

Nó được thiết kế để được sử dụng như sau

from future import standard_library
standard_library.install_aliases[]

Và sau đó, các lần nhập Py3 bình thường này hoạt động trên cả Py3 và Py2

import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg    # on Windows only
import test.support
import html, html.parser, html.entites
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server

import _thread
import _dummy_thread
import _markupbase

from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap     # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output              # even on Py2.6

[Các mô-đun và chức năng được đổi tên vẫn có sẵn dưới tên cũ của chúng trên Python 2. ]

Đây là một cách thay thế rõ ràng hơn cho thành ngữ này [xem http. // tài liệu. dấu trăn. com/python3_porting/py-porting. html]

try:
    import queue
except ImportError:
    import Queue as queue

Chúng tôi hiện không hỗ trợ các mô-đun này, nhưng muốn

import dbm
import dbm.dumb
import dbm.gnu
import collections.abc  # on Py33
import pickle     # should [optionally] bring in cPickle on Python 2

lớp tương lai. tiêu chuẩn_library. RenameImport[old_to_new]

Một lớp để nhập móc ánh xạ tên mô-đun Py3, v.v. tương đương với Py2

tương lai. tiêu chuẩn_library. cache_py2_modules[]

Hiện tại chức năng này không cần thiết, vì chúng tôi không cố gắng cung cấp móc nhập cho các mô-đun có tên mơ hồ. email, urllib, dưa chua

tương lai. tiêu chuẩn_library. detect_hook[]

Trả về True nếu móc nhập đã được cài đặt, Sai nếu không

tương lai. tiêu chuẩn_library. disable_hooks[]

không dùng nữa. Thay vào đó, hãy sử dụng remove_hooks[]. Điều này sẽ bị xóa bởi

try:
    import queue
except ImportError:
    import Queue as queue
1 v1. 0

tương lai. tiêu chuẩn_library. enable_hooks[]

không dùng nữa. Thay vào đó, hãy sử dụng install_hooks[]. Điều này sẽ bị xóa bởi

try:
    import queue
except ImportError:
    import Queue as queue
1 v1. 0

lớp tương lai. tiêu chuẩn_library. exclude_local_folder_imports[*args]

Trình quản lý bối cảnh ngăn không cho các mô-đun thư viện chuẩn như trình cấu hình được nhập từ thư mục nguồn tương lai python cục bộ trên Py3

[Điều này là cần thiết trước v0. 16. 0 vì sự hiện diện của thư mục trình cấu hình sẽ ngăn các công cụ thiết lập chạy trên Py3. Có lẽ nó không cần thiết nữa?]

tương lai. tiêu chuẩn_library. from_import[module_name , * . symbol_names, **kwargs]Example use:

>>> HTTPConnection = from_import['http.client', 'HTTPConnection']
>>> HTTPServer = from_import['http.server', 'HTTPServer']
>>> urlopen, urlparse = from_import['urllib.request', 'urlopen', 'urlparse']

Tương đương với cái này trên Py3

>>> from module_name import symbol_names[0], symbol_names[1], ...

và cái này trên Py2

>>> from future.moves.module_name import symbol_names[0], ...

hoặc là

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass
0

ngoại trừ việc nó cũng xử lý các tên mô-đun chấm, chẳng hạn như

try:
    import queue
except ImportError:
    import Queue as queue
3

lớp tương lai. tiêu chuẩn_library. móc

Hoạt động như một người quản lý bối cảnh. Lưu trạng thái của sys. các mô-đun và khôi phục nó sau khối 'với'

Sử dụng như thế này

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass
1

Để làm việc này, http. khách hàng sẽ bị xóa khỏi sys. các mô-đun sau khối 'với'. Bằng cách đó, các mô-đun được nhập trong khối 'với' sẽ tiếp tục có thể truy cập được trong không gian tên hiện tại chứ không phải từ bất kỳ mô-đun đã nhập nào [như yêu cầu]

tương lai. tiêu chuẩn_library. nhập_[tên_mô-đun , backport=False]

Truyền tên mô-đun [có khả năng chấm] của mô-đun thư viện chuẩn Python 3. Hàm này nhập mô-đun tương thích trên Py2 và Py3 và trả về mô-đun cấp cao nhất

Ví dụ sử dụng

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass
2

sau đó

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass
3

Sử dụng như sau

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass
4

Trên Py3, tương đương với cái này

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass
5

Trên Py2, tương đương với điều này nếu backport=False

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass
6

hoặc cái này nếu backport=True

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass
7

ngoại trừ việc nó cũng xử lý các tên mô-đun có dấu chấm, chẳng hạn như

try:
    import queue
except ImportError:
    import Queue as queue
3 Hiệu ứng sau đó giống như thế này

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass
8

Lưu ý rằng đây sẽ là một SyntaxError trong Python

b = bytes[b'ABCD']
assert list[b] == [65, 66, 67, 68]
assert repr[b] == "b'ABCD'"
assert [65, 66] in b

# These raise TypeErrors:
# b + u'EFGH'
# b.split[u'B']
# bytes[b','].join[[u'Fred', u'Bill']]


s = str[u'ABCD']

# These raise TypeErrors:
# s.join[[b'Fred', b'Bill']]
# s.startswith[b'A']
# b'B' in s
# s.find[b'A']
# s.replace[u'A', b'a']

# This raises an AttributeError:
# s.decode['utf-8']

assert repr[s] == 'ABCD'      # consistent repr with Py3 [no u prefix]


for i in range[10**11][:10]:
    pass
9

tương lai. tiêu chuẩn_library. install_aliases[]

Khỉ vá thư viện tiêu chuẩn trong Py2. 6/7 để cung cấp bí danh để tương thích với Py3 tốt hơn

tương lai. tiêu chuẩn_library. install_hook[]

Chức năng này cài đặt tương lai. standard_library nhập móc vào sys. meta_path

tương lai. tiêu chuẩn_library. is_py2_stdlib_module[m]

Cố gắng suy luận xem mô-đun m có phải từ thư viện chuẩn Python 2 hay không. Điều này có thể không đáng tin cậy trên tất cả các hệ thống

tương lai. tiêu chuẩn_library. remove_hooks[scrub_sys_modules=Sai]

Chức năng này loại bỏ hook nhập khẩu khỏi sys. meta_path

tương lai. tiêu chuẩn_library. restore_sys_modules[đã xóa]

Thêm bất kỳ mô-đun nào đã xóa trước đó trở lại hệ thống. bộ nhớ cache mô-đun, nhưng chỉ khi nó an toàn để làm như vậy

tương lai. tiêu chuẩn_library. scrub_future_sys_modules[]

không dùng nữa

tương lai. tiêu chuẩn_library. scrub_py2_sys_modules[]

Xóa mọi mô-đun thư viện chuẩn Python 2 khỏi

try:
    import queue
except ImportError:
    import Queue as queue
5 có thể can thiệp vào quá trình nhập kiểu Py3 bằng móc nhập. Ví dụ là các mô-đun có cùng tên [như urllib hoặc email]

[Lưu ý rằng các hook nhập hiện tại bị vô hiệu hóa đối với các mô-đun như thế này với các tên mơ hồ…]

lớp tương lai. tiêu chuẩn_library. suspend_hooks

Hoạt động như một người quản lý bối cảnh. Sử dụng như thế này

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
0

Nếu các móc bị vô hiệu hóa trước ngữ cảnh, chúng sẽ không được cài đặt khi ngữ cảnh còn lại

Một lựa chọn các chức năng tương thích chéo cho Python 2 và 3

Mô-đun này xuất các chức năng hữu ích cho mã tương thích 2/3

  • bind_method. liên kết các hàm với các lớp

  • try:
        import queue
    except ImportError:
        import Queue as queue
    
    6 và
    try:
        import queue
    except ImportError:
        import Queue as queue
    
    7

  • try:
        import queue
    except ImportError:
        import Queue as queue
    
    8. luôn bằng với đối tượng chuỗi nền tảng gốc [vì điều này có thể bị che khuất bởi các lần nhập từ tương lai. nội trang]

  • danh sách. lrange[], lmap[], lzip[], lfilter[]

  • khả năng tương thích phương pháp lặp lại
    • iteritems, iterkeys, itervalues

    • viewitem, viewkeys, viewvalues

    Chúng sử dụng phương thức ban đầu nếu có, nếu không thì chúng sử dụng các mục, khóa, giá trị

  • các loại

    • dạng văn bản. unicode trong Python 2, str trong Python 3

    • string_types. chuỗi cơ sở trong Python 2, str trong Python 3

    • nhị phân. str trong Python 2, byte trong Python 3

    • số nguyên_types. [int, long] trong Python 2, int trong Python 3

    • lớp_types. [loại, loại. ClassType] trong Python 2, nhập Python 3

  • bchr[c]

    Lấy một số nguyên và tạo một chuỗi byte gồm 1 ký tự

  • biên giới[c]

    Lấy kết quả lập chỉ mục trên chuỗi byte và tạo một số nguyên

  • tobyte

    Lấy một chuỗi văn bản, một chuỗi byte hoặc một chuỗi ký tự được lấy từ một chuỗi byte và tạo một chuỗi byte

  • nâng_từ[]

  • raise_with_traceback[]

Mô-đun này cũng định nghĩa các bộ trang trí này

  • try:
        import queue
    except ImportError:
        import Queue as queue
    
    9

  • import dbm
    import dbm.dumb
    import dbm.gnu
    import collections.abc  # on Py33
    import pickle     # should [optionally] bring in cPickle on Python 2
    
    0

  • import dbm
    import dbm.dumb
    import dbm.gnu
    import collections.abc  # on Py33
    import pickle     # should [optionally] bring in cPickle on Python 2
    
    1

Một số chức năng trong mô-đun này đến từ các nguồn sau

  • Jinja2 [được cấp phép BSD. xem https. //github. com/mitsuhiko/jinja2/blob/master/LICENSE]

  • Pandas mô-đun tương thích pandas. tương thích

  • sáu. py của Benjamin Peterson

  • Django

tương lai. đồ dùng. as_native_str[mã hóa=']

Trình trang trí để biến một hàm hoặc lệnh gọi phương thức trả về văn bản, tôi. e. unicode, thành một mã trả về nền tảng gốc str

Sử dụng nó như một trang trí như thế này

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
1

tương lai. đồ dùng. binary_type

bí danh của

tương lai. đồ dùng. bind_method[cls , tên, func]

Liên kết một phương thức với lớp, tương thích với python 2 và python 3

cls loại

lớp để nhận phương thức ràng buộc

tên chuỗi cơ sở

tên của phương thức trên thể hiện của lớp

chức năng chức năng

chức năng được ràng buộc như phương pháp

Không có

tương lai. đồ dùng. exec_[nguồn , toàn cầu=None, locals=None, /]

Thực thi nguồn đã cho trong ngữ cảnh toàn cầu và địa phương

Nguồn có thể là một chuỗi đại diện cho một hoặc nhiều câu lệnh Python hoặc đối tượng mã được trả về bởi compile[]. Toàn cầu phải là một từ điển và các địa phương có thể là bất kỳ ánh xạ nào, mặc định là toàn cầu và địa phương hiện tại. Nếu chỉ toàn cầu được đưa ra, thì người dân địa phương sẽ mặc định nó

tương lai. đồ dùng. implements_iterator[cls]

Từ jinja2/_compat. py. Giấy phép. BSD

Sử dụng như một trang trí như thế này

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
2

tương lai. đồ dùng. is_new_style[cls]

Trăn 2. 7 có cả lớp kiểu mới và kiểu cũ. Các lớp kiểu cũ có thể gây khó chịu trong một số trường hợp, chẳng hạn như khi sử dụng tính kế thừa. Sử dụng chức năng này để kiểm tra xem một lớp có phải là kiểu mới không. [Python 3 chỉ có các lớp kiểu mới. ]

tương lai. đồ dùng. isbyte[obj] Không dùng nữa. Sử dụng.

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
3

sau lần nhập này

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
4

tương lai. đồ dùng. mã định danh[s , dấu chấm=False]

Một chức năng tương đương với str. phương pháp định danh trên Py3

tương lai. đồ dùng. isint[obj]

không dùng nữa. Kiểm tra xem một đối tượng là Py3

import dbm
import dbm.dumb
import dbm.gnu
import collections.abc  # on Py33
import pickle     # should [optionally] bring in cPickle on Python 2
3 hay Py2
import dbm
import dbm.dumb
import dbm.gnu
import collections.abc  # on Py33
import pickle     # should [optionally] bring in cPickle on Python 2
3 hoặc
import dbm
import dbm.dumb
import dbm.gnu
import collections.abc  # on Py33
import pickle     # should [optionally] bring in cPickle on Python 2
5

Thay vì sử dụng chức năng này, bạn có thể sử dụng

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
5

Các thành ngữ sau đây là tương đương

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
6

tương lai. đồ dùng. isnewbytes[obj]

Nói cách khác, tương đương với kết quả của

import dbm
import dbm.dumb
import dbm.gnu
import collections.abc  # on Py33
import pickle     # should [optionally] bring in cPickle on Python 2
6, nó THỰC SỰ là một phiên bản newbytes, không phải đối tượng str gốc Py2?

Lưu ý rằng điều này không bao gồm các lớp con của byte mới và nó không tương đương với ininstance[obj, newbytes]

tương lai. đồ dùng. istext[obj] Không dùng nữa. Sử dụng.

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
7

sau lần nhập này

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
8

tương lai. đồ dùng. iteritems[obj , *kwargs]

Chỉ sử dụng cái này nếu khả năng tương thích với các phiên bản Python trước 2. 7 là bắt buộc. Nếu không, hãy ưu tiên viewitems[]

tương lai. đồ dùng. iterkey[obj , *kwargs]

Chỉ sử dụng cái này nếu khả năng tương thích với các phiên bản Python trước 2. 7 là bắt buộc. Mặt khác, thích viewkeys[]

tương lai. đồ dùng. giá trị lặp đi lặp lại[obj , *kwargs]

Chỉ sử dụng cái này nếu khả năng tương thích với các phiên bản Python trước 2. 7 là bắt buộc. Nếu không, hãy ưu tiên viewvalues[]

tương lai. đồ dùng. gốc[obj]

Trên Py3, đây là một lệnh cấm. bản địa [obj] -> obj

Trên Py2, trả về các loại Py2 gốc tương ứng là các siêu lớp cho các đối tượng được nhập từ Py3

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
9

from future import standard_library
standard_library.install_aliases[]
0

from future import standard_library
standard_library.install_aliases[]
1

from future import standard_library
standard_library.install_aliases[]
2

Các kiểu gốc hiện có trên Py2 sẽ được trả về không thay đổi

from future import standard_library
standard_library.install_aliases[]
3

tương lai. đồ dùng. gốc_byte

bí danh của

tương lai. đồ dùng. native_str

bí danh của

tương lai. đồ dùng. native_str_to_bytes[s , mã hóa='utf-8']

Trên Py3, trả về một chuỗi được mã hóa. Trên Py2, trả về loại newbytes, bỏ qua đối số

import dbm
import dbm.dumb
import dbm.gnu
import collections.abc  # on Py33
import pickle     # should [optionally] bring in cPickle on Python 2
9

tương lai. đồ dùng. old_div[a , b]

KHÔNG DÙNG. thay vào đó hãy nhập

>>> HTTPConnection = from_import['http.client', 'HTTPConnection']
>>> HTTPServer = from_import['http.server', 'HTTPServer']
>>> urlopen, urlparse = from_import['urllib.request', 'urlopen', 'urlparse']
0 từ
>>> HTTPConnection = from_import['http.client', 'HTTPConnection']
>>> HTTPServer = from_import['http.server', 'HTTPServer']
>>> urlopen, urlparse = from_import['urllib.request', 'urlopen', 'urlparse']
1

Tương đương với

>>> HTTPConnection = from_import['http.client', 'HTTPConnection']
>>> HTTPServer = from_import['http.server', 'HTTPServer']
>>> urlopen, urlparse = from_import['urllib.request', 'urlopen', 'urlparse']
2 trên Python 2 mà không có
>>> HTTPConnection = from_import['http.client', 'HTTPConnection']
>>> HTTPServer = from_import['http.server', 'HTTPServer']
>>> urlopen, urlparse = from_import['urllib.request', 'urlopen', 'urlparse']
3

LÀM. khái quát hóa điều này cho các đối tượng khác [như mảng, v.v. ]

tương lai. đồ dùng. python_2_unicode_ compatible[cls]

Một trình trang trí xác định các phương thức __unicode__ và __str__ trong Python 2. Trong Python 3, trình trang trí này không hoạt động

Để hỗ trợ Python 2 và 3 với một cơ sở mã duy nhất, hãy xác định phương thức __str__ trả về văn bản unicode và áp dụng trình trang trí này cho lớp, như thế này

from future import standard_library
standard_library.install_aliases[]
4

from future import standard_library
standard_library.install_aliases[]
5

from future import standard_library
standard_library.install_aliases[]
6

Sau đó, sau lần nhập này

class VerboseList[list]:
    def append[self, item]:
        print['Adding an item']
        super[].append[item]        # new simpler super[] function
8

sau đây là

>>> HTTPConnection = from_import['http.client', 'HTTPConnection']
>>> HTTPServer = from_import['http.server', 'HTTPServer']
>>> urlopen, urlparse = from_import['urllib.request', 'urlopen', 'urlparse']
4 trên cả Python 3 và 2

from future import standard_library
standard_library.install_aliases[]
8

Thật

và, trên thiết bị đầu cuối hỗ trợ Unicode với phông chữ phù hợp, cả hai đều in các ký tự tiếng Trung cho Khổng Tử

from future import standard_library
standard_library.install_aliases[]
9

Việc thực hiện đến từ django. đồ dùng. mã hóa

tương lai. đồ dùng. tăng_[tp , giá trị=None, tb=None]

Một chức năng phù hợp với Python 2. x

>>> HTTPConnection = from_import['http.client', 'HTTPConnection']
>>> HTTPServer = from_import['http.server', 'HTTPServer']
>>> urlopen, urlparse = from_import['urllib.request', 'urlopen', 'urlparse']
5 tuyên bố. Điều này cho phép tăng lại các ngoại lệ với giá trị cls và truy nguyên trên Python 2 và 3

tương lai. đồ dùng. raise_with_traceback[exc , traceback=Ellipsis]

Tăng ngoại lệ với truy nguyên hiện có. Nếu truy nguyên không được thông qua, hãy sử dụng sys. exc_info[] để lấy lại dấu vết

tương lai. đồ dùng. tăng giá[tp , giá trị=None, tb=None]

Một chức năng phù hợp với Python 2. x

>>> HTTPConnection = from_import['http.client', 'HTTPConnection']
>>> HTTPServer = from_import['http.server', 'HTTPServer']
>>> urlopen, urlparse = from_import['urllib.request', 'urlopen', 'urlparse']
5 tuyên bố. Điều này cho phép tăng lại các ngoại lệ với giá trị cls và truy nguyên trên Python 2 và 3

tương lai. đồ dùng. text_type

bí danh của

tương lai. đồ dùng. tobyte[s]

Mã hóa thành latin-1 [trong đó 256 ký tự đầu tiên giống như ASCII. ]

tương lai. đồ dùng. các mục xem[obj , *kwargs]

Chức năng lặp lại các mục từ điển có cùng hành vi giống như tập hợp trên Py2. 7 như trên Py3

Truyền kwargs cho phương thức

tương lai. đồ dùng. các phím xem[obj , *kwargs]

Chức năng lặp lại các khóa từ điển có cùng hành vi giống như tập hợp trên Py2. 7 như trên Py3

Truyền kwargs cho phương thức

tương lai. đồ dùng. giá trị lượt xem[obj , *kwargs]

Chức năng lặp lại các giá trị từ điển có cùng hành vi giống như tập hợp trên Py2. 7 như trên Py3

Truyền kwargs cho phương thức

tương lai. đồ dùng. with_metaclass[meta , *bases]

Chức năng từ jinja2/_compat. py. Giấy phép. BSD

Sử dụng nó như thế này

import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg    # on Windows only
import test.support
import html, html.parser, html.entites
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server

import _thread
import _dummy_thread
import _markupbase

from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap     # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output              # even on Py2.6
0

Điều này đòi hỏi một chút giải thích. ý tưởng cơ bản là tạo một siêu dữ liệu giả cho một cấp độ khởi tạo lớp thay thế chính nó bằng siêu dữ liệu thực tế. Do kiểm tra loại nội bộ, chúng tôi cũng cần đảm bảo rằng chúng tôi hạ cấp siêu dữ liệu tùy chỉnh cho một cấp xuống mức gần với loại hơn [đó là lý do tại sao __call__ và __init__ trở lại từ loại, v.v. ]

Điều này có lợi thế hơn sáu. with_metaclass không giới thiệu các lớp giả vào MRO cuối cùng

Phục hồi một số chức năng cũ từ Python 2 để sử dụng trong Python 3. Chúng nên được sử dụng một cách tiết kiệm, để hỗ trợ các nỗ lực chuyển, vì mã sử dụng chúng không còn là mã Python 3 tiêu chuẩn nữa

Mô-đun này cung cấp những điều sau đây

  1. Việc triển khai các hàm dựng sẵn này không tương đương trên Py3

  • ứng dụng

  • chr

  • cmp

  • tập tin thực thi

  1. bí danh

  • thực tập sinh

Chủ Đề