简体   繁体   中英

Do .pyc files contain type hinting information?

I assumed standard library type hinting support was all based on reading the plain source like inspect does for some things, but I looked at typing.py in the standard library and it seems the compiler does store type hint info on the object itself.

So, if I do:

def myfunc(a: int, b:int): -> str
    return "{a} + {b} = {a+b}"

and then compile that to a .pyc file, does the type information stick around such that someone who I've given the .pyc file can use things like typing.get_type_hints() to access it? (With the assumption that I have a valid reason to distribute just the .pyc.)

You already answered your question here:

but I looked at typing.py in the standard library and it seems the compiler does store type hint info on the object itself.

This means that typing information doesn't get lost and gets compiled with the rest of your code which is an obvious behavior. You can simply test that by creating a .pyc file from your python file and then importing the compiled module and testing it as following. Also note that you have a syntax error in your code. You should move the : after -> str :

In [38]: import py_compile

In [39]: py_compile.compile('ex.py')
Out[39]: '__pycache__/ex.cpython-35.pyc'

In [40]: cd __pycache__/
/home/kasra/Desktop/__pycache__

In [41]: import ex

In [42]: ex.myfunc
Out[42]: <function ex.myfunc(a:int, b:int) -> str>

In [43]: import typing

In [44]: typing.get_type_hints(ex.myfunc)
Out[44]: {'a': int, 'b': int, 'return': str}

Well I have just impersonated your someone here :) with your code and the answer is yes it works, after I changed the def myfunc(a: int, b:int): -> str to

def myfunc(a: int, b:int) -> str:

otherwise it's a syntax error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM