1

I need to call a list that I made in a function that's in another file. I was trying attempting this below, but I am getting the error cannot import name 'names' from 'backend'. Does anyone know how this can be achieved without making a class?

import backend
from backend import names
word = names
print (word)

Error message:

File "C:/Users/user/OneDrive/Desktop/Pokemon/weather.py", line 52, in <module>
  from backend import names
  builtins.ImportError: cannot import name 'names' from 'backend'

The code form the other file is

import const 

SEP = ','

def get_pokemon_stats():
    """Reads the data contained in a pokemon data file and parses it into
    several data structures.

    Args:
        None

    Returns: a tuple of:
        -a dict where:
            -each key is a pokemon name (str)
            -each value is a tuple of the following stats:
                -pokemon name (str)
                -species_id (int)
                -height (float)
                -weight (float)
                -type_1 (str)
                -type_2 (str)
                -url_image (str)
                -generation_id (int)
                -evolves_from_species_id (str)
        -a dict where:
            -each key is a pokemon species_id (int)
            -each value is the corresponding pokemon name (str)
        -a list of all pokemon names (strs)
        -a dict where:
            -each key is a pokemon type (str). Note that type_1 and type_2
            entries are all considered types. There should be no special
            treatment for the type NA; it is considered a type as well.
            -each value is a list of all pokemon names (strs) that fall into
            the corresponding type
    """
    name_to_stats = {}
    id_to_name = {}
    names = []
    pokemon_by_type = {}
    DATA_FILENAME = 'pokemon.csv' 


    with open(const.DATA_FILENAME) as f:
        header_to_col_num = parse_header(f)
        for line in f:
            info = line.split(const.SEP)
            name = (info[(header_to_col_num['pokemon'])])
            col_names = ('pokemon', 'species_id', 'height', 'weight', 'type_1', 
            'type_2',
            'url_image', 'generation_id', 'evolves_from_species_id',)
            value = [info[header_to_col_num[col]] for col in col_names]
            value[1] = int(value[1])
            value[2] = float(value[2])
            value[3] = float(value[3])
            value[7] = int(value[7])
            value = tuple(value)

            name_to_stats[name] = value

            species_id = int(info[(header_to_col_num['species_id'])])
            id_to_name[species_id] = name
            names.append(name)


        for name, info in name_to_stats.items():
            type1 = info[4]
            type2 = info[5]
            if type1 in pokemon_by_type:
                pokemon_by_type[type1].append(name)
            else:
                pokemon_by_type[type1] = [name]
            if type2 in pokemon_by_type:
                pokemon_by_type[type2].append(name)
            else:
                pokemon_by_type[type2] = [name]


        return name_to_stats, id_to_name, names, pokemon_by_type
  • You'll need to show the full traceback here – roganjosh Nov 21 '18 at 20:56
  • Your error doesn't match your code, in your code you're not trying to import `pokemon_names`. Please show your other file's code and the correct traceback. – Aurora Wang Nov 21 '18 at 20:56
  • Sorry I am not familliar with the term traceback? – Meliodus123 Nov 21 '18 at 20:57
  • 1
    The full error message that usually starts with "Traceback (most recent call last)" – Michael Butscher Nov 21 '18 at 21:01
  • It seems that `backend` just doesn't define an identifier `names` (a class, function or variable with that name). – Michael Butscher Nov 21 '18 at 21:03
  • File "C:/Users/user/OneDrive/Desktop/Pokemon/weather.py", line 52, in from backend import names builtins.ImportError: cannot import name 'names' from 'backend' - Thats the full error message I don't see anything about a traceback – Meliodus123 Nov 21 '18 at 21:05
  • 2
    Could you edit your question to add your other file's code? – Aurora Wang Nov 21 '18 at 21:11
  • `names` is a local variable in the `get_pokemon_stats` function. Local variables are not visible outside the function that defines them. Also, you never call the function. – Barmar Nov 21 '18 at 21:32
  • Instead of saying "the other file," can you refer to the file(s) by its (their) name(s)? If you define a `function1` in `file1.py`, you can put `file1.py` in the same directory as `file2.py`, and in `file2.py`, `from file1 import function1`. You can also make it far more complicated than that. – Evan Nov 21 '18 at 22:29
  • Possible duplicate of [Call a function from another file in Python](https://stackoverflow.com/questions/20309456/call-a-function-from-another-file-in-python) – Evan Nov 21 '18 at 22:32

2 Answers2

0

According to Python's documentation:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Thus, the reason why you can't import your names list from another file is because names is inside your get_pokemon_stats function scope and it is not a global variable.

You can make names global putting it outside your function and declaring it as global to use inside your function:

...
names = []
def get_pokemon_stats():
    ...
    global names
    ...

However, you should consider carefully if you really want to do this. names will only contain actual values once you call your get_pokemon_stats function. Nevertheless, you should avoid just declaring variables globally if you don't really understand how local and global variables work and when we should use them.

I recommend that you consider doing the following code instead:

from backend import get_pokemon_stats
_, _, word, _ = get_pokemon_stats()
print (word)
Aurora Wang
  • 1,822
  • 14
  • 22
0

You need to call the get_pokemon_stats function. It returns four values, and the third value is names.

import backend
name_to_stats, id_to_name, names, pokemon_by_type = backend.get_pokemon_stats()
print(names)
Barmar
  • 741,623
  • 53
  • 500
  • 612