简体   繁体   中英

Help with accessing module variable inside Python function?

I have the following function in a Python module called dictbuilder.py:

def my_dictbuilder(reader_o, writer):
    fieldnames = ('name', 'number')
    reader = csv.DictReader(reader_o, fieldnames = fieldnames, delimiter="\t")
    my_dict = {}
    id = 0
    for row in reader:
       id += 1
       my_dict[id] = row['name'], row['number']
       id += 1
    return(my_dict)

I have imported and called this function from a module called main.py. I would like to also use the my_dict variable from the dictbuilder.py module I have imported into main.py. When I try to print my_dictbuilder.mydict I get this error:

AttributeError: 'function' object has no attribute 'my_dict'

Can anyone help me figure out how to access the my_dict variable from my main.py file? Thanks for the help!

Well, you're returning my_dict , so just store the return value in your main module when you call it.

my_dict = dictbuilder.my_dictbuilder(reader_o, writer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM