2

Creating a class for data frames generation, I generated a list of the str format of variables names (e.g. variable x was represented in the list as 'x'). In order to use the elements of the generated list of strings as variables, I used both vars() and globals() for the same purpose in different functions as vars() did not work in functions.

In: my_num = 100

In: vars()['my_num']
Out: 100

In: globals()['my_num']
Out: 100

As a result, I noticed the issue that using vars() in functions it is impossible to use the output of these functions for other ones. This is the example with vars() used which did not work as the output provided list of str only without generating corresponding variables in the global environment:

def pair_lines(all_lines, titles):
    matrix = pd.DataFrame(columns=titles, index=titles)
    out = []
    for n1, i1, numb1 in zip(titles, all_lines, range(0, len(titles))):
        for n2, i2, numb2 in zip(titles, all_lines, range(0, len(titles))):
            if n1 == n2:
                continue
            if '{}_{}'.format(n2,n1) in out:
                continue
            else:
                x = '{}_{}'.format(n1,n2)
                vars()[x] = pd.merge(i1, i2, on='Gene_ID', how = 'inner')
                out.append(x)
                matrix.iloc[numb1, numb2] = float(len(vars()[x]))
    return out

Changing vars() to globals() fixed the issue.

Why so and what is the difference between vars() and globals()?

Thank you in advance!

0 Answers0