python variable sharing between packages/modules

前端 未结 3 1728
离开以前
离开以前 2021-01-23 16:02

trying to understand and learn how to write packages... testing with something i\'ve always used, logging...

Can you please help me understand why the \'log\' variable i

3条回答
  •  礼貌的吻别
    2021-01-23 16:50

    Your main.py doesn't do anything to define the name log in the global namespace. Importing a module can define names in the namespace of that module, but can't put anything in the global namespace.

    In your main.py you should add this statement:

    from clusterlogging.differentlogging import log
    

    By the way, I that is such a long module name, I would use import as:

    import clusterlogging.differentlogging as difflogging
    log = difflogging.log
    

    EDIT: I originally recommended this but it won't work:

    from difflogging import log  # doesn't work
    

    You might even want to use a really short name like dl:

    import clusterlogging.differentlogging as dl
    dl.log('whatever')
    

    Since dl is really short, maybe you don't need to get log bound in the global namespace.

    Also, you could get every name from a module by using import * but this is not recommended.

    from clusterlogging.differentlogging import *  # not recommended
    

    You usually don't want to clutter the global namespace with all the stuff defined in a module. Import just what you need. This is tidier and helps document what you are actually using.

提交回复
热议问题