pythonfunctionvariablesconfigparser

How to access the variables declared inside functions in python


I have the following code that reads the configuration file and stores the results in some variables as a list

import ConfigParser

def read_config_file():
    config = ConfigParser.ConfigParser()
    cnf_path = 'config_files/php.sr'
    config.read(cnf_path)
    if config.has_section('basic'):
        if config.has_option('basic', 'basic'):
            php_bsc_mdls = config.get('basic', 'basic').split(',')
    if config.has_section('advance'):
        if config.has_option('advance','advance'):
            php_adv_mdls = config.get('advance', 'advance').split(',')

Now i want to get the result variables php_bsc_mdls and php_adv_mdls from the function something like read_config_file.php_bsc_mdls or read_config_file.php_adv_mdls

So is it possible to access/get the variables from the python function ?


Solution

  • You just need to return them. They cease to exist when the function ends.

    def read_config_file():
        config = ConfigParser.ConfigParser()
        cnf_path = 'config_files/php.sr'
        config.read(cnf_path)
        if config.has_section('basic'):
            if config.has_option('basic', 'basic'):
                php_bsc_mdls = config.get('basic', 'basic').split(',')
        if config.has_section('advance'):
            if config.has_option('advance','advance'):
                php_adv_mdls = config.get('advance', 'advance').split(',')
    
        if php_bsc_mdls and php_adv_bls:
            return php_bsc_mdls,php_adv_mdls
        elif php_bsc_mdls:
            return php_bsc_mdls, None
    

    Other approach would be a class where you save them to class variables. And later get those values from the class, not the function.

    Or like this:

    def read_config_file():
        php_bsc_mdls = None
        php_adv_mdls = None
        config = ConfigParser.ConfigParser()
        cnf_path = 'config_files/php.sr'
        config.read(cnf_path)
        if config.has_section('basic'):
            if config.has_option('basic', 'basic'):
                php_bsc_mdls = config.get('basic', 'basic').split(',')
        if config.has_section('advance'):
            if config.has_option('advance','advance'):
                php_adv_mdls = config.get('advance', 'advance').split(',')
    
        return php_bsc_mdls, php_adv_mdls
    

    In either case, you need to check the return values where ever you call the function. If the values are none or not.