【问题标题】:How to mimic the use of "import module" when I have to use "from module import method"当我必须使用“从模块导入方法”时如何模仿“导入模块”的使用
【发布时间】:2020-05-16 20:59:15
【问题描述】:

Google OAuth2 implementation in Python 被包装成我必须这样做的方式

from google.oauth2 import service_account

credentials = service_account.Credentials...

由于我更喜欢​​明确说明我的外部方法的来源,所以我更喜欢

import google.oauth2

credentials = google.oauth2.service_account.Credentials...

但这不起作用,an answer to another question 巧妙地解释了原因(也有很多 other good 外植,或多或少的离子深度)。

有没有办法模仿“完整路径符号”,以便我可以使用第二个版本,但限制迫使我使用from module import ...

我试过了

from google.oauth2 import service_account as google.oauth2.service_account

credentials = google.oauth2.service_account.Credentials....

但我明白了

  File "d:\Nextcloud\dev-perso\testing\googlecalendar\googlecalendar.py", line 4
    from google.oauth2 import service_account as google.oauth2.service_account
                                                       ^
SyntaxError: invalid syntax

还有其他解决方案,还是我坚持使用短名称?

注意:我可以

from google.oauth2 import service_account as google_oauth2_service_account

credentials = google_oauth2_service_account.Credentials...

但这并不是那么优雅(这是一个主观意见,如果没有更好的解决方案,我最终会使用它)

【问题讨论】:

  • 您必须是 Java 程序员 ;-) 使用短名称,并使您的模块短,这样就不会混淆名称的来源 - 此外您不需要打字这么多,其他程序员不需要读这么多,而且你正在遵循标准的 Python 做事方式(这是双赢的!)
  • 你确实意识到如果你想使用ˋgoogle.oauth2.service_accountˋ,你必须ˋimport google.oauth2.service_accountˋ,而不仅仅是ˋimport google.oauth2ˋ?
  • @thebjorn ˋgoogleˋ 是一个外部包,它不能由 OP 来改变它的布局。
  • @MisterMiyagi 我的意思是使用from google.oauth2 import service_account,就像其他 Python 程序员希望你做的那样(包括为这个包编写文档的人)。
  • @thebjorn:不,我只是 10 年左右的业余/家庭 Python 开发人员。我发现使用frac 而不是math.extended.rationsl.frac 会使阅读代码变得更加困难。但正如我所提到的,这是主观的,与问题无关。我很高兴你认识世界上所有的 Python 程序员,因为“每个人”都会使用缩写形式。

标签: python python-3.x python-import python-module


【解决方案1】:

您可以使用绝对路径导入模块service_account

import google.oauth2.service_account
google.oauth2.service_account.Credentials
#<class 'google.oauth2.service_account.Credentials'>

【讨论】:

    猜你喜欢
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 2021-12-08
    • 2020-07-26
    相关资源
    最近更新 更多