How to get a list of variables in specific Python module?

前端 未结 5 817
野趣味
野趣味 2020-11-30 10:42

Let\'s assume I have the following file structure:

data.py

foo = []
bar = []
abc = \"def\"

core.py

5条回答
  •  误落风尘
    2020-11-30 11:43

    This is the version I wrote for python 3.7 (it excludes the internal dunder methods via the condition in the comprehension)

    print([v for v in dir(data) if v[:2] != "__"])
    

    A longer but complete working example is below:

    """an example of a config file whose variables may be accessed externally"""
    # Module variables
    server_address = "172.217.167.68"
    server_port = 8010
    server_to_client_port = 8020
    client_to_server_port = 8030
    client_buffer_length = 4096
    server_buffer_length = 2048
    
    def printVariables(variable_names):
        """Renders variables and their values on the terminal."""
        max_name_len = max([len(k) for k in variable_names])
        max_val_len = max([len(str(globals()[k])) for k in variable_names])
    
        for k in variable_names:
            print(f'  {k:<{max_name_len}}:  {globals()[k]:>{max_val_len}}')
    
    if __name__ == "__main__":
        print(__doc__)
        ks = [k for k in dir() if (k[:2] != "__" and not callable(globals()[k]))]
        printVariables(ks)
    
    

    The above code outputs:

    an example of a config file whose variables may be accessed externally
      client_buffer_length :            4096
      client_to_server_port:            8030
      server_address       :  172.217.167.68
      server_buffer_length :            2048
      server_port          :            8010
      server_to_client_port:            8020
    

提交回复
热议问题