six.PY2 返回一个表示当前运行环境是否为python2的boolean值

six.PY3 返回一个表示当前运行环境是否为python3的boolean值

import six,sys

print(six.PY2)    #python2结果为True
print(six.PY3)    #python3结果为True

sys.version_info[0]    #PY2 = 2
sys.version_info[0]    #PY3 = 3
sys.version_info[0:2]  #PY34>= (3, 4)

常量

  • six.class_types

这里主要是针对python中的old-style和new-style, new-style为type, old-style为 types.ClassType。

python2中同时有old-style和new-style,python3中只有new-style。

  • six.integer_types

这里针对python2和python3中各自支持的int类型进行了区分:在python2中,存在 int 和 long 两种整数类型;在python3中,仅存在一种类型int。

  • six.string_types

这里针对python2和python3中各自的string类型进行了区分:在python2中,使用的为basestring;在python3中,使用的为str。

  • six.text_type

这里针对python2和python3中的文本字符进行了区分:在python2中,使用的文本字符的类型为unicode;在python3中使用的文本字符的类型为str。

具体可以参考Python2 与 Python3 的编码对比

  • six.MAXSIZE

list、string、dict以及其他的容器所能支持的最大尺寸。

if PY3:
    string_types = str,
    integer_types = int,
    class_types = type,
    text_type = str
    binary_type = bytes

    MAXSIZE = sys.maxsize
else:
    string_types = basestring,
    integer_types = (int, long)
    class_types = (type, types.ClassType)
    text_type = unicode
    binary_type = str

    if sys.platform.startswith("java"):
        # Jython always uses 32 bits.
        MAXSIZE = int((1 << 31) - 1)
    else:
        # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
        class X(object):

            def __len__(self):
                return 1 << 31
        try:
            len(X())
        except OverflowError:
            # 32-bit
            MAXSIZE = int((1 << 31) - 1)
        else:
            # 64-bit
            MAXSIZE = int((1 << 63) - 1)
        del X

对象模型兼容

  • six.get_unbound_function(meth)

针对python2和python3中unbound function的支持不同,在python2中存在unbound function,在python3中不存在unbound function。

if PY3:
    def get_unbound_function(unbound):
        return unbound
else:
    def get_unbound_function(unbound):
        return unbound.im_func

有关的测试代码如下:

>>> class Foo():
...     def bar():
...             print(1)
...     def too(self):
...             print(2)
...
>>>

在python2的环境中:

>>> Foo.bar
<unbound method Foo.bar>
>>> Foo().bar
<bound method Foo.bar of <__main__.Foo instance at 0x10e8a7998>>
>>> Foo.too
<unbound method Foo.too>
>>> Foo().too
<bound method Foo.too of <__main__.Foo instance at 0x10e8a7998>>

在python3的环境中:

>>> Foo.bar
<function Foo.bar at 0x10ebe4bf8>
>>> Foo().bar
<bound method Foo.bar of <__main__.Foo object at 0x10ebeaa58>>
>>> Foo.too
<function Foo.too at 0x10ebe4c80>
>>> Foo().bar
<bound method Foo.bar of <__main__.Foo object at 0x10ebeaa58>>

使用six.get_unbound_function(meth):

在python2环境中:

>>> import six
>>> six.get_unbound_function(Foo.too)
<function too at 0x10e89faa0>
>>> six.get_unbound_function(Foo.bar)
<function bar at 0x10e89fa28>

在python3环境中:

>>> import six
>>> six.get_unbound_function(Foo.too)
<function Foo.too at 0x10a158c80>
>>> six.get_unbound_function(Foo.bar)
<function Foo.bar at 0x10a158bf8>
  • six.get_method_function(meth)

此方法可以在方法对象之外得到函数。在python2中使用im_func, 在python3中使用__func__

if PY3:
    _meth_func = "__func__"
else:
    _meth_func = "im_func"
get_method_function = operator.attrgetter(_meth_func)

有关的测试代码如下:

>>> class Foo():
...     def bar():
...             print(1)
...     def too(self):
...             print(2)
...
>>>

在python2环境中:

>>> import six
>>> six.get_method_function(Foo().bar)
<function bar at 0x10c8c6a28>
>>> six.get_method_function(Foo.bar)
<function bar at 0x10c8c6a28>
>>> six.get_method_function(Foo().too)
<function too at 0x10c8c6aa0>
>>> six.get_method_function(Foo.too)
<function too at 0x10c8c6aa0>

在python3环境中:

>>> import six
>>> six.get_method_function(Foo.bar)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__func__'
>>> six.get_method_function(Foo().bar)
<function Foo.bar at 0x1047dbbf8>
>>> six.get_method_function(Foo.too)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__func__'
>>> six.get_method_function(Foo().too)
<function Foo.too at 0x1047dbc80>
  • six.get_method_self(meth)

针对python2以及python3中的不同,返回bound method的self。其中:python2中使用im_self,python3中使用__self__。

if PY3:
    _meth_self = "__self__"
else:
    _meth_self = "im_self"
get_method_self = operator.attrgetter(_meth_self)

有关的测试代码如下:

>>> class Foo():
...     def bar():
...             print(1)
...     def too(self):
...             print(2)
...
>>>

在python2的环境中:

>>> import six
>>> six.get_method_self(Foo.bar)
>>> a = six.get_method_self(Foo.bar)
>>> a
>>> six.get_method_self(Foo().bar)
<__main__.Foo instance at 0x10563da70>
>>> a = six.get_method_self(Foo().bar)
>>> a
<__main__.Foo instance at 0x10563dd88>
>>> six.get_method_self(Foo.too)
>>> a = six.get_method_self(Foo.too)
>>> a
>>> six.get_method_self(Foo().too)
<__main__.Foo instance at 0x10563da28>
>>> a = six.get_method_self(Foo().too)
>>> a
<__main__.Foo instance at 0x10563da70>

在python3的环境中:

>>> import six
>>> six.get_method_self(Foo.bar)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__self__'
>>> six.get_method_self(Foo().bar)
<__main__.Foo object at 0x1059bbb00>
>>> six.get_method_self(Foo.too)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__self__'
>>> six.get_method_self(Foo().too)
<__main__.Foo object at 0x1059bbb38>
  • six.get_function_closure(func)

针对python2和python3中的不同,返回函数当中的闭包。其中,python2使用func_closure,python3使用 __closure__。

if PY3:
    _func_closure = "__closure__"
else:
    _func_closure = "func_closure"

get_function_closure = operator.attrgetter(_func_closure)

关于闭包的理解可以参考:

  1. 浅显理解 Python 闭包
  2. 闭包的概念、形式与应用

有关的测试代码如下:

>>> def foo(n):
...     a = 1
...     def bar(n):
...             return a-n
...     return bar

此处需要注意的是foo函数返回的是bar函数,而不是具体的值。

在python2的环境当中:

>>> foo.__closure__
>>> foo(1)
<function bar at 0x10c25aa28>
>>> foo(1).__closure__
(<cell at 0x10c25eb40: int object at 0x7f9460d0bca8>,)
>>> foo(1).func_closure
(<cell at 0x10c25ed70: int object at 0x7f9460d0bca8>,)

在python3的环境当中:

>>> foo.__closure__
>>> foo(1)
<function foo.<locals>.bar at 0x10c46dbf8>
>>> foo(1).__closure__
(<cell at 0x10c451198: int object at 0x10be73170>,)
>>> foo(1).func_closure
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'func_closure'
  • six.get_function_code(func)

针对python2和python3中获取func中的code对象,将使用不同的方式进行获取。在python2中,将使用func_code;在python3中,将使用code。

if PY3:
    _func_code = "__code__"
else:
    _func_code = "func_code"
get_function_code = operator.attrgetter(_func_code)

如果你对其中的code object是什么比较感兴趣,可以参考下面的资料:

  1. Exploring Python Code Objects

有关的测试代码如下:

>>> def boo():
...     return 1

在python2的环境当中:

>>> boo.func_code
<code object boo at 0x1101092b0, file "<stdin>", line 1>
>>> boo().func_code
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'func_code'

在python3的环境当中:

>>> boo.__code__
<code object boo at 0x104d8a930, file "<stdin>", line 1>
>>> boo().__code__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__code__'
  • six.get_function_defaults(func)

针对python2和python3中的区别,获取func中的默认元组。在python2中,使用func_defaults;在python3中,使用__defaults__

if PY3:
    _func_defaults = "__defaults__"
else:
    _func_defaults = "func_defaults"
get_function_defaults = operator.attrgetter(_func_defaults)

有关的测试代码如下:

>>> def boo(a=1):
...     return a
...

在python2环境中:

>>> boo.func_defaults
(1,)
>>> boo.__defaults__
(1,)
>>> boo().func_defaults
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'func_defaults'
>>> boo().__defaults__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__defaults__'

在python3环境中:

>>> boo.__defaults__
(1,)
>>> boo.func_defaults
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'func_defaults'
>>> boo().__defaults__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__defaults__'
>>> boo().func_defaults
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'func_defaults'
  • six.get_function_globals(func)

获取函数当中的全局变量。在python2中,使用func_globals;在python3中,使用__globals__

if PY3:
    _func_globals = "__globals__"
else:
    _func_globals = "func_globals"
get_function_globals = operator.attrgetter(_func_globals)

有关的测试代码:

>>> def boo(a=1):
...     x = 100
...     b = x - a
...     return b

在python2环境中:

>>> boo.__globals__
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'boo': <function boo at 0x109a6e9b0>, '__doc__': None, '__package__': None}
>>> boo.func_globals
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'boo': <function boo at 0x109a6e9b0>, '__doc__': None, '__package__': None}

在python3环境中:

>>> boo.__globals__
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'boo': <function boo at 0x1029d8e18>}
>>> boo.func_globals
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'func_globals'
  • six.next(it) or six.advance_iterator(it)

获取到迭代器的下一个。在python2环境中,使用it.next();在python3环境中,使用next(it)

try:
    advance_iterator = next
except NameError:
    def advance_iterator(it):
        return it.next()
next = advance_iterator

关于迭代器的内容可以参考一下文件:

  1. 迭代器

在python2环境中:

>>> it = iter([1,2,3,4,5])
>>> while True:
...     try:
...             x = it.next()
...     except NameError:
...             print "name error"
...     except StopIteration:
...             print "end"
...             break
...
end

>>> it = iter([1,2,3,4,5])
>>> while True:
...     try:
...             x = next(it)
...     except NameError:
...             print "name error"
...     except StopIteration:
...             print "end"
...             break
...
end

在python3环境中:

>>> it = iter([1,2,3,4,5])
>>> while True:
...     try:
...             x = it.next()
...     except NameError:
...             print("name error")
...     except StopIteration:
...             print("end")
...             break
...
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
AttributeError: 'list_iterator' object has no attribute 'next'

>>> it = iter([1,2,3,4,5])
>>> while True:
...     try:
...             x = next(it)
...     except NameError:
...             print("name error")
...     except StopIteration:
...             print("end")
...             break
...
end
  • six.callable(obj)

该方法用来检验obj是否可以进行调用。

关于python的callable属性,请参考一下文件:

try:
    callable = callable
except NameError:
    def callable(obj):
        return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)

有关的测试代码:

>>> def add(x, y):
...     return x + y
...

在python2环境中:

>>> callable(add)
True

在python 3.1环境中:

>>> callable(add)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'callable' is not defined

在python3.2之后的环境中:

>>> callable(add)
True

python之six用法的更多相关文章

  1. Python回调函数用法实例详解

    本文实例讲述了Python回调函数用法.分享给大家供大家参考.具体分析如下: 一.百度百科上对回调函数的解释: 回调函数就是一个通过函数指针调用的函数.如果你把函数的指针(地址)作为参数传递给另一个函 ...

  2. day01-day04总结- Python 数据类型及其用法

    Python 数据类型及其用法: 本文总结一下Python中用到的各种数据类型,以及如何使用可以使得我们的代码变得简洁. 基本结构 我们首先要看的是几乎任何语言都具有的数据类型,包括字符串.整型.浮点 ...

  3. 【Python】关于Python有意思的用法

    开一篇文章,记录关于Python有意思的用法,不断更新 1.Python树的遍历 def sum(t): tmp=0 for k in t: if not isinstance(k,list): tm ...

  4. python中xrange用法分析

    本文实例讲述了python中xrange用法.分享给大家供大家参考.具体如下: 先来看如下示例: >>> x=xrange(0,8) >>> print x xra ...

  5. 浅谈Python在信息学竞赛中的运用及Python的基本用法

    浅谈Python在信息学竞赛中的运用及Python的基本用法 前言 众所周知,Python是一种非常实用的语言.但是由于其运算时的低效和解释型编译,在信息学竞赛中并不用于完成算法程序.但正如LRJ在& ...

  6. python scapy的用法之ARP主机扫描和ARP欺骗

    python scapy的用法之ARP主机扫描和ARP欺骗 目录: 1.scapy介绍 2.安装scapy 3.scapy常用 4.ARP主机扫描 5.ARP欺骗 一.scapy介绍 scapy是一个 ...

  7. python函数的用法

    python函数的用法 目录: 1.定义.使用函数 1.函数定义:def 2.函数调用:例:myprint() 3.函数可以当作一个值赋值给一个变量 例:a=myprint()    a() 4.写r ...

  8. python 中@ 的用法【转】

    这只是我的个人理解: 在Python的函数中偶尔会看到函数定义的上一行有@functionName的修饰,当解释器读到@的这样的修饰符之后,会先解析@后的内容,直接就把@下一行的函数或者类作为@后边的 ...

  9. Python Enum 枚举 用法汇总

    Python Enum 枚举 用法汇总 import os import sys if sys.version_info.major + sys.version_info.minor * 0.1 &l ...

  10. python查看对象用法

    python查看类用法: dir(object_name)

随机推荐

  1. Android开源经典项目

    目前包括: Android开源项目第一篇--个性化控件(View)篇   包括ListView.ActionBar.Menu.ViewPager.Gallery.GridView.ImageView. ...

  2. 解决Cell重用内容混乱的几种简单方法,有些方法会增加内存

    重用实现分析 查看UITableView头文件,会找到NSMutableArray*  visiableCells,和NSMutableDictnery* reusableTableCells两个结构 ...

  3. git使用中checkout生成临时br的问题(吓出一身冷汗啊)

    git中几天前漫不经心的使用了git checkout ver_hash的命令,结果push到远程库都提示everything is up-to-date,实际神马都没提交上去啊!但看本地log中的确 ...

  4. ruby调用Office Jet引擎压缩access数据库

    由于单位业务需要,搭建一台服务器专门用来做数据存储.因为数据流很小,遂采用access库作为DB.开始还好,但是后来发现access数据库有一问题,就是表空间会随着使用越来越大,哪怕表里没有数据.因为 ...

  5. 《转》xcode创建一个工程的多个taget,便于测试和发布多个版本

    背景:很多时候,我们需要在一个工程中创立多个target,也就是说我们希望同一份代码可以创建两个应用,放到模拟器或者真机上,或者是,我们平时有N多人合作开发,当测试的时候,在A这里装了一遍测A写的那块 ...

  6. candy(贪心)

    [题目] There are N children standing in a line. Each child is assigned a rating value. You are giving ...

  7. CRT 重启Was

    输入用户名.密码登陆以后 # ps -eaf | grep websphere 找到路径 /usr/IBM/WebSphere/AppServer/ 进入/usr/IBM/WebSphere/AppS ...

  8. Shell排序(改良的插入排序)

    Shell排序算法最初是由D.L Shell于1959年提出,假设要排序的元素有n个,则每个进行插入排序是并不是所偶的元素同时进行,而是去一段间隔. Shell首先将间隔设定为n/2,然后跳跃的进行插 ...

  9. git merge 与 rebase

    git merge git rebase merge V.S. rebase 参考材料 写在开始: 对merge和rebase的用法总有疑惑,好像两个都能完成"获取别的branch的comm ...

  10. Django1.10 release notes摘编

    一.重点新特性: 1.面向PostgreSQL的全文搜索支持 2.新式风格的middleware 3.用户名Unicode编码的官方支持 二.一些可以提的改变: 1.用户名最大长度增加到150 2.不 ...