How to get most recent globals variables everytime a function as ran

I’m creating a function that get a list of all the global dataframes in memory and does something with them. Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df1 = pd.DataFrame()
df2 = pd.DataFrame()
def func():
# Get all dataframes in memory
alldfs = [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)]
# do something
return dict(zip(tables_filtered, [ps.from_pandas(globals()[table]) for table in tables_filtered]))
func() # returns df1 and df2
df3 = pd.DataFrame()
func() # returns df1 and df2
</code>
<code>df1 = pd.DataFrame() df2 = pd.DataFrame() def func(): # Get all dataframes in memory alldfs = [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)] # do something return dict(zip(tables_filtered, [ps.from_pandas(globals()[table]) for table in tables_filtered])) func() # returns df1 and df2 df3 = pd.DataFrame() func() # returns df1 and df2 </code>
df1 = pd.DataFrame()
df2 = pd.DataFrame()

def func():
    # Get all dataframes in memory
    alldfs = [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)]
    
    # do something

    return dict(zip(tables_filtered, [ps.from_pandas(globals()[table]) for table in tables_filtered]))

func()  # returns df1 and df2

df3 = pd.DataFrame()

func()  # returns df1 and df2

The issue is that the global variables at the time of creation are stored and used everytime I run the function, but I want it to read the most up to date globals everytime its ran. So if 5 more dataframes are created after, it will return those.

Originally, I was trying to write the function in another module and import it, but the globals wasn’t working so now doing it in the same notebook but having the same issue.

UPDATE

Okay to add more context since it seems like this is a bad approach. My goal was to pack the pyspark.sql feature into a function so that others using the notebook could easily just write sql queries on the dataframes:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def get_all_dataframes():
return = [name for name,var in globals().items() if isinstance(var, pd.core.frame.DataFrame)]
def query_data(query):
# Gather all dataframes saved in memory
dataframes = get_all_dataframes()
# Find all table names after FROM or JOIN
tables = re.findall(r'FROMs+(w+)|JOINs+(w+)', query, re.IGNORECASE)
tables = [table for sublist in tables for table in sublist if table]
tables_found = []
# Check if tables exist in memory and replace them with curly brackets
for table in tables:
if table in dataframes:
query = re.sub(r'b' + table + r'b', f'{{{table}}}', query)
if table not in tables_found:
tables_found.append(table)
else:
raise ValueError(f"Table '{table}' does not exist in memory.")
# Create the query args and turn Pandas DF into a Pyspark DF
print(f"Tables detected: {tables_found}")
query_args = dict(zip(tables_found, [ps.from_pandas(globals()[table]) for table in tables_found]))
def _run_query(**query_args):
return ps.sql(
query,
**query_args
).to_pandas()
query_results = _run_query(**query_args)
print(f"Table created with {query_results.shape[0]:,} rows and {query_results.shape[1]:,} columns.")
return query_results
</code>
<code>def get_all_dataframes(): return = [name for name,var in globals().items() if isinstance(var, pd.core.frame.DataFrame)] def query_data(query): # Gather all dataframes saved in memory dataframes = get_all_dataframes() # Find all table names after FROM or JOIN tables = re.findall(r'FROMs+(w+)|JOINs+(w+)', query, re.IGNORECASE) tables = [table for sublist in tables for table in sublist if table] tables_found = [] # Check if tables exist in memory and replace them with curly brackets for table in tables: if table in dataframes: query = re.sub(r'b' + table + r'b', f'{{{table}}}', query) if table not in tables_found: tables_found.append(table) else: raise ValueError(f"Table '{table}' does not exist in memory.") # Create the query args and turn Pandas DF into a Pyspark DF print(f"Tables detected: {tables_found}") query_args = dict(zip(tables_found, [ps.from_pandas(globals()[table]) for table in tables_found])) def _run_query(**query_args): return ps.sql( query, **query_args ).to_pandas() query_results = _run_query(**query_args) print(f"Table created with {query_results.shape[0]:,} rows and {query_results.shape[1]:,} columns.") return query_results </code>
def get_all_dataframes():
    return = [name for name,var in globals().items() if isinstance(var, pd.core.frame.DataFrame)]



def query_data(query):
    # Gather all dataframes saved in memory
    dataframes = get_all_dataframes()
    
    # Find all table names after FROM or JOIN
    tables = re.findall(r'FROMs+(w+)|JOINs+(w+)', query, re.IGNORECASE)
    tables = [table for sublist in tables for table in sublist if table]

    tables_found = []
    # Check if tables exist in memory and replace them with curly brackets
    for table in tables:
        if table in dataframes:
            query = re.sub(r'b' + table + r'b', f'{{{table}}}', query)
            if table not in tables_found:
                tables_found.append(table)
        else:
            raise ValueError(f"Table '{table}' does not exist in memory.")

    # Create the query args and turn Pandas DF into a Pyspark DF
    print(f"Tables detected: {tables_found}")
    query_args = dict(zip(tables_found, [ps.from_pandas(globals()[table]) for table in tables_found]))

    def _run_query(**query_args):
        return ps.sql(
            query, 
            **query_args
        ).to_pandas()

    query_results = _run_query(**query_args)
    print(f"Table created with {query_results.shape[0]:,} rows and {query_results.shape[1]:,} columns.")

    return query_results

So that way, instead of having to write this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>ps.sql('''
SELECT m1.a, m2.b
FROM {table1} m1 INNER JOIN {table2} m2
ON m1.key = m2.key
ORDER BY m1.a, m2.b''',
table1=ps.from_pandas(table1),
table2=ps.from_pandas(table2))
</code>
<code>ps.sql(''' SELECT m1.a, m2.b FROM {table1} m1 INNER JOIN {table2} m2 ON m1.key = m2.key ORDER BY m1.a, m2.b''', table1=ps.from_pandas(table1), table2=ps.from_pandas(table2)) </code>
ps.sql('''
  SELECT m1.a, m2.b
  FROM {table1} m1 INNER JOIN {table2} m2
  ON m1.key = m2.key
  ORDER BY m1.a, m2.b''',
  table1=ps.from_pandas(table1),
  table2=ps.from_pandas(table2))

You can just write this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>run_query(
"""
SELECT m1.a, m2.b
FROM table1 m1 INNER JOIN table2 m2
ON m1.key = m2.key
ORDER BY m1.a, m2.b
"""
)
</code>
<code>run_query( """ SELECT m1.a, m2.b FROM table1 m1 INNER JOIN table2 m2 ON m1.key = m2.key ORDER BY m1.a, m2.b """ ) </code>
run_query(
"""
SELECT m1.a, m2.b
  FROM table1 m1 INNER JOIN table2 m2
  ON m1.key = m2.key
  ORDER BY m1.a, m2.b
"""
)

This is a simple example. The queries are much more complex. And the reason for the sql is that I’m transitioning a lot of code to Python and a lot of the transformations were using PROC SQL (SAS). So in order for the end user to be able to make changes a bit easier.

7

Use globals()

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import pandas as pd
df1 = pd.DataFrame()
df2 = pd.DataFrame()
def func():
# Get all dataframes in memory
alldfs = [name for name,var in globals().items() if isinstance(var, pd.core.frame.DataFrame)]
# do something
return alldfs
print(func()) # returns df1 and df2
df3 = pd.DataFrame()
print(func())
</code>
<code>import pandas as pd df1 = pd.DataFrame() df2 = pd.DataFrame() def func(): # Get all dataframes in memory alldfs = [name for name,var in globals().items() if isinstance(var, pd.core.frame.DataFrame)] # do something return alldfs print(func()) # returns df1 and df2 df3 = pd.DataFrame() print(func()) </code>
import pandas as pd


df1 = pd.DataFrame()
df2 = pd.DataFrame()

def func():
    # Get all dataframes in memory
    alldfs = [name for name,var in globals().items() if isinstance(var, pd.core.frame.DataFrame)]

    # do something

    return alldfs

print(func())  # returns df1 and df2

df3 = pd.DataFrame()
print(func())

This outputs

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>$ python myfile.py
['df1', 'df2']
['df1', 'df2', 'df3']
</code>
<code>$ python myfile.py ['df1', 'df2'] ['df1', 'df2', 'df3'] </code>
$ python myfile.py
['df1', 'df2']
['df1', 'df2', 'df3']

This clearly contains df3, the newly created df, which is also in global scope

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật