[英]Get a module's attribute's type without importing the module or attribute
我正在使用 python 對.py 文件進行一些處理。 這些.py 文件可能來自未知來源,因此我不希望直接運行它們的代碼(出於安全考慮),並且可能沒有安裝它們的依賴項。 我正在使用 python 的tokenize
模塊分析這些文件,然后使用這些標記來查看任何 NAME 標記的類型。 對於在文件中聲明的 function 或 class ,您可以執行以下操作:
import tokenize
# tokenize the source file ...
all_functions = []
for index, token in enumerate(tokens):
# check the token type
if token[0] == tokenize.NAME:
# check the token's string
if token[1] == "def":
# the next token is always the name of the function
all_functions.append(tokens[index + 1][1])
elif token[1] == "class":
# as above but for classes ...
問題是對於導入的模塊,我不知道如何在沒有看到其聲明的情況下區分 class 和 function 之間的區別。
采取以下代碼片段:
import pathlib
foo = pathlib.Path("some/path")
bar = pathlib.urlquote_from_bytes(b"some bytes")
因為這是編寫良好的代碼(符合PEP8 ),我可以假設pathlib.Path
將是 class 因為第一個字符是大寫的,我可以假設pathlib.urlquote_from_bytes
將是 function 因為它使用帶下划線的小寫單詞,但是如果沒有模塊的源代碼(可能並非如此),我無法確定。 並非我收到的所有 .py 文件都一定寫得很好(符合PEP8 ),所以我不能依賴這個。
有沒有其他方法可以找出某些 python 模塊的屬性是否屬於給定類型? 我的一個想法是運行python3 -m py_compile <file>
然后分析 result.pyc 文件,但我從未研究過 cpython 所以我不知道這是否真的有用。 歡迎大家提出意見。
對於這個特定的用例,事實證明我不需要分離出類和函數,並且可以將它們全部包裝為callables 。 可調用對象本質上是具有__call__()
方法的任何實例,例如某些方法x(arg1, arg2, ...)
是x.__call__(arg1, arg2, ...)
...) 的簡寫。
For anyone using older versions of Python it is worth noting that "this function was first removed in Python 3.0 and then brought back in Python 3.2."
進一步閱讀:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.