python locals()再探索 以及from .xx import xxx

本文详细解析了Python中locals()函数的工作原理及应用场景。通过实例展示了该函数如何收集不同作用域内的局部变量,并解释了它在模块级别和函数级别中的表现差异。
def locals(): # real signature unknown; restored from __doc__
    """
    locals() -> dictionary
    
    Update and return a dictionary containing the current scope's local variables.重点
    """

    return {}


以前也知道这个函数,还是在使用django的时候用到了。今天看源码的时候觉得以前理解的不透彻。

首先:

调用这个函数返回一个字典     locals() -> dictionary

第二,也是最重要的,到底是收集的哪些域空间变量。以下是我的认识:

得看locals()出现的位置,模块内

a = 'dsd'
vb = 'dsd'
cc = locals()

大家可以打印看看cc是什么,有助于理解locals(),你也可以试试

a = 'dsd'
cc = locals()
vb = 'dsd'

函数内情况:

def test():
    a = 1
    b = 2
    c =3
    def test2():
        d = 4
        e = 5
        f = 6
    return locals()

这里的locals() = {'a': 1, 'c': 3, 'test2': <function test2 at 0x02C256F0>, 'b': 2}

总结,locals()所收集的变量由她所在的位置的域决定,可以理解成locals()是一个变量,他只收集和它平级的变量

from .xx import xx

from .. xx import xx

. 和 ..  什么意思(其实是目录关系)

.代表所在文件的当前目录

..代表所在文件的当前目录父目录


lib

   | te

   |__init__

   |c.py

   |d.py

__intit__

fs.py

c.py内的文件

from ..import fs
from .import d



转载于:https://my.oschina.net/012345678/blog/303802

但是我pip的时候却报错:Installing build dependencies ... error error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> [71 lines of output] Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple Ignoring numpy: markers 'python_version == "3.6" and platform_system != "AIX" and platform_python_implementation == "CPython"' don't match your environment Ignoring numpy: markers 'python_version == "3.6" and platform_system != "AIX" and platform_python_implementation != "CPython"' don't match your environment Ignoring numpy: markers 'python_version == "3.7" and platform_system != "AIX"' don't match your environment Ignoring numpy: markers 'python_version == "3.6" and platform_system == "AIX"' don't match your environment Ignoring numpy: markers 'python_version == "3.7" and platform_system == "AIX"' don't match your environment Ignoring numpy: markers 'python_version >= "3.8" and platform_system == "AIX"' don't match your environment Collecting setuptools Using cached https://pypi.tuna.tsinghua.edu.cn/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl (1.2 MB) Collecting wheel Using cached https://pypi.tuna.tsinghua.edu.cn/packages/0b/2c/87f3254fd8ffd29e4c02732eee68a83a1d3c346ae39bc6822dcbcb697f2b/wheel-0.45.1-py3-none-any.whl (72 kB) Collecting Cython>=0.28.5 Downloading https://pypi.tuna.tsinghua.edu.cn/packages/c2/94/65ba40faeafe74845ba22b61aff7d73475671c3bd24bffc6cba53f3b0063/cython-3.1.2-cp313-cp313-win_amd64.whl (2.7 MB) ---------------------------------------- 2.7/2.7 MB 11.0 MB/s eta 0:00:00 Collecting numpy==1.17.3 Downloading https://pypi.tuna.tsinghua.edu.cn/packages/b6/d6/be8f975f5322336f62371c9abeb936d592c98c047ad63035f1b38ae08efe/numpy-1.17.3.zip (6.4 MB) ---------------------------------------- 6.4/6.4 MB 11.1 MB/s eta 0:00:00 Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing metadata (pyproject.toml): started Preparing metadata (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error Preparing metadata (pyproject.toml) did not run successfully. exit code: 1 [28 lines of output] Running from numpy source directory. <string>:418: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates Traceback (most recent call last): File "D:\Python\Projects\SymbolicRegression\.venv\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module> main() ~~~~^^ File "D:\Python\Projects\SymbolicRegression\.venv\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ~~~~^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python\Projects\SymbolicRegression\.venv\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 149, in prepare_metadata_for_build_wheel return hook(metadata_directory, config_settings) File "C:\Users\18982\AppData\Local\Temp\pip-build-env-iylv62ta\overlay\Lib\site-packages\setuptools\build_meta.py", line 374, in prepare_metadata_for_build_wheel self.run_setup() ~~~~~~~~~~~~~~^^ File "C:\Users\18982\AppData\Local\Temp\pip-build-env-iylv62ta\overlay\Lib\site-packages\setuptools\build_meta.py", line 512, in run_setup super().run_setup(setup_script=setup_script) ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\18982\AppData\Local\Temp\pip-build-env-iylv62ta\overlay\Lib\site-packages\setuptools\build_meta.py", line 317, in run_setup exec(code, locals()) ~~~~^^^^^^^^^^^^^^^^ File "<string>", line 443, in <module> File "<string>", line 422, in setup_package File "C:\Users\18982\AppData\Local\Temp\pip-install-cnhfnw94\numpy_33d7182cc1bd44368e579191210a5ae4\numpy\distutils\__init__.py", line 6, in <module> from . import ccompiler File "C:\Users\18982\AppData\Local\Temp\pip-install-cnhfnw94\numpy_33d7182cc1bd44368e579191210a5ae4\numpy\distutils\ccompiler.py", line 111, in <module> replace_method(CCompiler, 'find_executables', CCompiler_find_executables) ^^^^^^^^^ NameError: name 'CCompiler' is not defined. Did you mean: 'ccompiler'? [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed Encountered error while generating package metadata. See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. [notice] A new release of pip is available: 23.2.1 -> 25.1.1 [notice] To update, run: python.exe -m pip install --upgrade pip [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. [notice] A new release of pip is available: 23.2.1 -> 25.1.1 [notice] To update, run: python.exe -m pip install --upgrade pip (base) (.venv) PS D:\Python\Projects\SymbolicRegression> pip uninstall scikit-learn Found existing installation: scikit-learn 1.7.1 Uninstalling scikit-learn-1.7.1: Would remove: d:\python\projects\symbolicregression\.venv\lib\site-packages\scikit_learn-1.7.1.dist-info\* d:\python\projects\symbolicregression\.venv\lib\site-packages\sklearn\* Proceed (Y/n)? y Successfully uninstalled scikit-learn-1.7.1 (base) (.venv) PS D:\Python\Projects\SymbolicRegression> pip install scikit-learn==0.20.4 -i https://pypi.tuna.tsinghua.edu.cn/simple Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple Collecting scikit-learn==0.20.4 Downloading https://pypi.tuna.tsinghua.edu.cn/packages/20/a0/5ec20d7e460d8ebde9ec5e40cda4339c5f546871c3a5bf9228f615b25618/scikit-learn-0.20.4.tar.gz (11.7 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 11.7/11.7 MB 11.5 MB/s eta 0:00:00 Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... error error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [29 lines of output] <string>:12: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. Partial import of sklearn during the build process. Traceback (most recent call last): File "<string>", line 153, in get_numpy_status ModuleNotFoundError: No module named 'numpy' Traceback (most recent call last): File "D:\Python\Projects\SymbolicRegression\.venv\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module> main() ~~~~^^ File "D:\Python\Projects\SymbolicRegression\.venv\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ~~~~^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python\Projects\SymbolicRegression\.venv\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 149, in prepare_metadata_for_build_wheel return hook(metadata_directory, config_settings) File "C:\Users\18982\AppData\Local\Temp\pip-build-env-uqmyyyrx\overlay\Lib\site-packages\setuptools\build_meta.py", line 374, in prepare_metadata_for_build_wheel self.run_setup() ~~~~~~~~~~~~~~^^ File "C:\Users\18982\AppData\Local\Temp\pip-build-env-uqmyyyrx\overlay\Lib\site-packages\setuptools\build_meta.py", line 512, in run_setup super().run_setup(setup_script=setup_script) ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\18982\AppData\Local\Temp\pip-build-env-uqmyyyrx\overlay\Lib\site-packages\setuptools\build_meta.py", line 317, in run_setup exec(code, locals()) ~~~~^^^^^^^^^^^^^^^^ File "<string>", line 250, in <module> File "<string>", line 238, in setup_package ImportError: Numerical Python (NumPy) is not installed. scikit-learn requires NumPy >= 1.8.2. Installation instructions are available on the scikit-learn website: http://scikit-learn.org/stable/install.html [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details.
最新发布
07-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值