ChanMan ChanMan - 1 month ago 12
Python Question

How to import and then reload without initial duplicate

def add():
import add_coffee_record
import imp
imp.reload(add_coffee_record)

def show():
import show_coffee_records
import imp
imp.reload(show_coffee_records)

def search():
import search_coffee_records
import imp
imp.reload(search_coffee_records)

def modify():
import modify_coffee_records
import imp
imp.reload(modify_coffee_records)

def delete():
import delete_coffee_record
import imp
imp.reload(delete_coffee_record)

def main():
num=input('\nEnter the number on the menu: ')
while num != '6':
if num == '1':
print()
add()
if num == '2':
print()
show()
if num == '3':
print()
search()
if num == '4':
print()
modify()
if num == '5':
print()
delete()
num=input('\nEnter the number on the menu: ')

main()


My output looks like so:

Enter the number on the menu: 2

Description: Thanksgiving Blend
Quantity: 300.0
Description: Christmas Blend
Quantity: 100.0
Description: Thanksgiving Blend
Quantity: 300.0
Description: Christmas Blend
Quantity: 100.0

Enter the number on the menu: 2

Description: Thanksgiving Blend
Quantity: 300.0
Description: Christmas Blend
Quantity: 100.0

Enter the number on the menu: 2

Description: Thanksgiving Blend
Quantity: 300.0
Description: Christmas Blend
Quantity: 100.0


I'd like it if the first output would not duplicate itself. Is there a way to structure the program where on the first instance "import" ONLY is used and on successive instances "reload" is used? Note: I cannot copy paste the program files instead of import. I need to use import. Thanks.

Answer

You could remove the module from sys.modules before importing it:

def add():
    sys.modules.pop("add_coffee_record")
    import add_coffee_record

Another option would be to call imp.load_module directly:

def add():
    imp.load_module("add_coffee_record", *imp.find_module("add_coffee_record"))
Comments