蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHON本地 Python 环境python3-type-conversion.py
python3-type-conversion.py28 行
"""蓝色天空网 mbsky.com: all conversion entries with bounded values and failure branches."""
from pathlib import Path
import sys,ast,json,math
sys.path.insert(0,str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
c=Checks()
def main():
    left=14;right=0.5;result=left+right;c.eq('implicit result',result,14.5);c.eq('inputs not retyped',(type(left).__name__,type(right).__name__),('int','float'));c.raises('int and text not automatic',TypeError,lambda:7+'25');c.eq('numeric conversion vs display',(int('25')+7,str(7)+'25'),(32,'725'))
    big=2**53+1;c.eq('float precision loss',int(float(big))==big,False)
    c.eq('int defaults/truncation',[int(),int(2.9),int(-2.9),int('25')],[0,2,-2,25]);c.eq('int bases',[int('ff',16),int('0o17',0)],[255,15]);c.raises('int decimal text invalid',ValueError,lambda:int('2.9'));c.raises('base needs text',TypeError,lambda:int(2.9,10));c.raises('int complex invalid',TypeError,lambda:int(1+2j))
    c.eq('float forms',[float(),float(2),float('4.5')],[0.0,2.0,4.5]);c.eq('float accepts inf',math.isinf(float('inf')),True);c.eq('float accepts nan',math.isnan(float('nan')),True);c.raises('float huge int',OverflowError,lambda:float(10**1000));c.raises('float bad text',ValueError,lambda:float('sky'));c.raises('float complex',TypeError,lambda:float(1+2j))
    c.eq('complex number',complex(2,3),2+3j);c.eq('complex text',complex('2+3j'),2+3j);c.raises('complex text and imag',TypeError,lambda:complex('2+3j',1))
    c.eq('str number/text',[str(2),str(3.0),str('sky')],['2','3.0','sky']);c.eq('str bool not numeric',str(True),'True');text='sky';c.eq('str may reuse identity',str(text)is text,True)
    class Debug:
        def __repr__(self):return '<owned debug label>'
    c.eq('repr not always evaluable',repr(Debug()),'<owned debug label>');c.eq('repr text has quotes',repr('sky'),"'sky'")
    c.eq('eval fixed owned expression',eval('3 * 5',{'__builtins__':{}}),15);c.eq('JSON data parsed',json.loads('{"site":"mbsky.com"}'),{'site':'mbsky.com'});c.eq('literal data only',ast.literal_eval('[2,3]'),[2,3]);c.raises('literal_eval not arithmetic',ValueError,lambda:ast.literal_eval('2+3'))
    c.eq('tuple iterable',tuple([2,3]),(2,3));t=(2,3);c.eq('tuple same tuple identity',tuple(t)is t,True);c.eq('list iterable',list((2,3)),[2,3]);inside=[[1]];copy=list(inside);c.eq('list new outer',copy is inside,False);c.eq('list shared inner',copy[0]is inside[0],True)
    c.eq('set',set([2,2,3]),{2,3});c.eq('dict mapping',dict({'sky':1}),{'sky':1});c.eq('dict pairs not just tuples',dict([['sky',1]]),{'sky':1});c.eq('dict kwargs',dict(sky=1),{'sky':1});c.raises('dict malformed pair',ValueError,lambda:dict([['sky',1,2]]));c.eq('dict duplicate later wins',dict([('sky',1),('sky',2)]),{'sky':2});c.eq('frozenset',frozenset([2,2,3]),frozenset({2,3}));c.eq('dict iterable gives keys',list({'sky':1}),['sky'])
    c.eq('chr boundaries',(chr(0),chr(0x10ffff)),('\x00','\U0010ffff'));c.eq('ord unicode',ord('天'),0x5929);c.eq('ord one byte',ord(b'A'),65);c.raises('chr outside range',ValueError,lambda:chr(0x110000));c.raises('ord too long',TypeError,lambda:ord('sky'))
    c.eq('radix strings',(hex(-15),oct(15),bin(15)),('-0xf','0o17','0b1111'));c.raises('hex float invalid',TypeError,lambda:hex(1.5));c.eq('ascii escaped',ascii('天'),"'\\u5929'")
    c.eq('bool text',[bool('0'),bool('False'),bool(''),bool()],[True,True,False,False]);c.eq('bytes from count',bytes(3),b'\x00\x00\x00');c.eq('bytes list edges',bytes([0,255]),b'\x00\xff');c.eq('bytes text encoding',bytes('天空','utf8'),'天空'.encode('utf8'));c.raises('bytes text no encoding',TypeError,lambda:bytes('天空'));c.raises('bytes outside range',ValueError,lambda:bytes([256]));c.raises('negative count',ValueError,lambda:bytes(-1));c.raises('invalid UTF8',UnicodeDecodeError,lambda:b'\xff'.decode('utf8'));c.eq('explicit replacement decoding',b'\xff'.decode('utf8',errors='replace'),'�')
    array=bytearray([0,255]);array[0]=65;c.eq('mutable bytearray',array,bytearray([65,255]));c.raises('bytearray outside range',ValueError,lambda:bytearray([-1]))
    data=bytearray(b'abc');view=memoryview(data);c.eq('writable memoryview',view.readonly,False);view[0]=ord('z');c.eq('view shares buffer',data,bytearray(b'zbc'));snapshot=view.tobytes();data[1]=ord('x');c.eq('tobytes copied',snapshot,b'zbc');c.eq('view sees later mutation',view.tobytes(),b'zxc');c.raises('live view blocks buffer resize',BufferError,lambda:data.append(4));view.release();c.raises('released view invalid',ValueError,lambda:view.tobytes());data.append(4);c.eq('resize after release',data,bytearray(b'zxc\x04'))
    readonly=memoryview(b'sky');c.eq('immutable bytes readonly',readonly.readonly,True);c.raises('readonly write fails',TypeError,lambda:readonly.__setitem__(0,1));readonly.release();c.raises('non-buffer invalid',TypeError,lambda:memoryview([1,2]))
    c.finish('python3-type-conversion',eval_input='fixed owned string only',memoryview_scope='real bytearray sharing and release')
if __name__=='__main__':main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python3-type-conversion.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python3-type-conversion.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习