0

I'm trying to append inputs to a list in another python file. I think I have the order correct but the error message I get is AttributeError: module 'inventory' has no attribute 'pick' when I try it out.

main.py:

import inventory

choice = input("--> ")

if "inv pick" in choice:
    inventory.pick()

inventory.py:

import main

backpack = []

def pick():
    """
    Function for picking up things
    """
    backpack.append(main.choice)
    print(backpack)

If I make write the string "inv pick flower" end hit enter I get the error message instead of the printed content of the list 'Backpack'. Maybe I should use .extend instead of .append but neither of it works right now. Any pointers perhaps?

Regards

Thomas Bengtsson
  • 399
  • 2
  • 10
  • 22
  • 1
    I think your problem is described at https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python – Michael Butscher Oct 08 '18 at 22:33
  • @MichaelButscher So they can't import each other? Then I have to use a third .py-file to somehow store and process? – Thomas Bengtsson Oct 08 '18 at 22:40
  • 1
    Read [here](https://stackoverflow.com/questions/3739654/how-to-fix-a-circular-dependency-for-imports) there's a fix. – Irfanuddin Oct 08 '18 at 22:40
  • @IrfanuddinShafi It worked insofar as there are no error messages but nothing gets printed though... – Thomas Bengtsson Oct 08 '18 at 22:49
  • Why don't you use the choice as a parameter for `pick()`? As it is, it's bad design. – Matthias Oct 08 '18 at 22:49
  • Generally you will not want to import `main` anywhere as that will re-run `main.py`. Instead, pass data as parameters from main to the functions in the other modules. – Stuart Oct 08 '18 at 23:30

1 Answers1

2

The following is a much better way to implement what you're trying to achieve without any problematic circular imports.

main.py:

import inventory

choice = input("--> ")


inventory.pick(choice)

inventory.py:

backpack = []

def pick(choice):

    backpack.append(choice)
    print(backpack)
Irfanuddin
  • 2,295
  • 1
  • 15
  • 29