Home > front end >  How to import function from another file?
How to import function from another file?

Time:04-05

I recently started learning Python and I am in a bit of a pickle right now. There are three files.

First file. main.py:

#the morse code
from MorseCode import*
from Check import product, Check_For_Alphas
Word1 = input("Enter the text") #text enter
Word = Word1.lower()
#print(Word)
Sentence_splited = list(Word) #the sentence is splited here in the form of a list
#print(Sentence_splited)
length = len(Sentence_splited)
#print(len(Sentence_splited),"elements") #used len() meathod to give length
count = 0 #this is for the loop

while count < length:
    #checks for the alphsbets needs improvement
    Check_For_Alphas()
    count = count 1
print(*product)#gives the morse code

And the second file

from Main_Program import Sentence_splited, count, length
from MorseCode import *

product = []
def Check_For_Alphas():
    if (Sentence_splited[length-(length-count)] == 'a'):
        product.append(CodeForAlpha['a'])
    elif(Sentence_splited[length-(length-count)] == 'b'):
        product.append(CodeForAlpha['b'])
    elif(Sentence_splited[length-(length-count)] == 'c'):
        product.append(CodeForAlpha['c'])
    elif(Sentence_splited[length-(length-count)] == 'd'):
        product.append(CodeForAlpha['d'])
    elif(Sentence_splited[length-(length-count)] == 'e'):
        product.append(CodeForAlpha['e'])
    elif(Sentence_splited[length-(length-count)] == 'f'):
        product.append(CodeForAlpha['f'])
    elif(Sentence_splited[length-(length-count)] == 'g'):
        product.append(CodeForAlpha['g'])
    elif(Sentence_splited[length-(length-count)] == 'h'):
        product.append(CodeForAlpha['h'])
    elif(Sentence_splited[length-(length-count)] == 'i'):
        product.append(CodeForAlpha['i'])
    elif(Sentence_splited[length-(length-count)] == 'j'):
        product.append(CodeForAlpha['j'])
    elif(Sentence_splited[length-(length-count)] == 'k'):
        product.append(CodeForAlpha['k'])
    elif(Sentence_splited[length-(length-count)] == 'l'):
        product.append(CodeForAlpha['l'])
    elif(Sentence_splited[length-(length-count)] == 'm'):
        product.append(CodeForAlpha['m'])
    elif(Sentence_splited[length-(length-count)] == 'n'):
        product.append(CodeForAlpha['n'])
    elif(Sentence_splited[length-(length-count)] == 'o'):
        product.append(CodeForAlpha['o'])
    elif(Sentence_splited[length-(length-count)] == 'p'):
        product.append(CodeForAlpha['p'])
    elif(Sentence_splited[length-(length-count)] == 'q'):
        product.append(CodeForAlpha['q'])
    elif(Sentence_splited[length-(length-count)] == 'r'):
        product.append(CodeForAlpha['r'])
    elif(Sentence_splited[length-(length-count)] == 's'):
        product.append(CodeForAlpha['s'])
    elif(Sentence_splited[length-(length-count)] == 't'):
        product.append(CodeForAlpha['t'])
    elif(Sentence_splited[length-(length-count)] == 'u'):
        product.append(CodeForAlpha['u'])
    elif(Sentence_splited[length-(length-count)] == 'v'):
        product.append(CodeForAlpha['v'])
    elif(Sentence_splited[length-(length-count)] == 'w'):
        product.append(CodeForAlpha['w'])
    elif(Sentence_splited[length-(length-count)] == 'x'):
        product.append(CodeForAlpha['x'])
    elif(Sentence_splited[length-(length-count)] == 'y'):
        product.append(CodeForAlpha['y'])
    elif(Sentence_splited[length-(length-count)] == 'z'):
        product.append(CodeForAlpha['z'])
    elif(Sentence_splited[length-(length-count)] == ' '):
        product.append(CodeForAlpha[' '])

here you just have to look at the first 5 to 6 lines the rest I checked. And here is the third file

CodeForAlpha = {
    "a": "._",
    "b": "_...",
    "c": "_._.",
    "d": "_..",
    "e": ".",
    "f": ".._.",
    "h": "....",
    "i": "..",
    "j": "._ _ _",
    "k": "_._",
    "l": "._..",
    "m": "_ _",
    "n": "_.",
    "o": "_ _ _",
    "p": "._ _.",
    "q": "_ _._",
    "r": "._.",
    "s": "...",
    "t": "_",
    "u": ".._",
    "v": "..._",
    "w": "._ _",
    "x": "_.._",
    "y": "_._ _",
    "z": "_ _..",
    " ": " "
}

I am unable to use the program. The error is:

  File "d:/download/JAVA PROJECT/Python_Project/Dict_Prototype/Main_Program.py", line 3, in <module>
    import Check
  File "d:\download\JAVA PROJECT\Python_Project\Dict_Prototype\Check.py", line 1, in <module>
    from Main_Program import Sentence_splited, count, length
  File "d:\download\JAVA PROJECT\Python_Project\Dict_Prototype\Main_Program.py", line 15, in <module>
    Check_For_Alphas()
NameError: name 'Check_For_Alphas' is not defined
```

CodePudding user response:

You've got a cross module import. The origin of problem is how Python works with imports. When you write constructions like from module import * or from module import func1, func2 then the module file gets executed.

Here you've got from Main_Program import Sentence_splited, count, length in the second file (which I assume is called Check.py) so it starts to run Main_program.py where you've got import from Check import product, Check_For_Alphas but Check.py was not initialized to the end as we are still only on line 2. That's why you are getting NameError. To fix this you can import modules only in functions you actually use them or import them via import module as in that case module will be executed only on first use of it (lazy loading of modules)

From the previous text if you write files like this:

Main_program.py

#the morse code
from MorseCode import*
import Check
Word1 = input("Enter the text")#text enter
Word = Word1.lower()
#print(Word)
Sentence_splited = list(Word)#the sentence is splited here in the form of a list
#print(Sentence_splited)
length = len(Sentence_splited)
#print(len(Sentence_splited),"elements")      #used len() meathod to give length
count = 0#this is for the loop

while count < length:
    #checks for the alphsbets needs improvement
    Check.Check_For_Alphas()
    count = count 1
print(*Check.product)#gives the morse code

Check.py

from MorseCode import *

product = []
def Check_For_Alphas():
    from Main_Program import Sentence_splited, count, length
    if (Sentence_splited[length-(length-count)] == 'a'):
        product.append(CodeForAlpha['a'])
    elif(Sentence_splited[length-(length-count)] == 'b'):
        product.append(CodeForAlpha['b'])
    elif(Sentence_splited[length-(length-count)] == 'c'):
        product.append(CodeForAlpha['c'])
    elif(Sentence_splited[length-(length-count)] == 'd'):
        product.append(CodeForAlpha['d'])
    elif(Sentence_splited[length-(length-count)] == 'e'):
        product.append(CodeForAlpha['e'])
    elif(Sentence_splited[length-(length-count)] == 'f'):
        product.append(CodeForAlpha['f'])
    elif(Sentence_splited[length-(length-count)] == 'g'):
        product.append(CodeForAlpha['g'])
    elif(Sentence_splited[length-(length-count)] == 'h'):
        product.append(CodeForAlpha['h'])
    elif(Sentence_splited[length-(length-count)] == 'i'):
        product.append(CodeForAlpha['i'])
    elif(Sentence_splited[length-(length-count)] == 'j'):
        product.append(CodeForAlpha['j'])
    elif(Sentence_splited[length-(length-count)] == 'k'):
        product.append(CodeForAlpha['k'])
    elif(Sentence_splited[length-(length-count)] == 'l'):
        product.append(CodeForAlpha['l'])
    elif(Sentence_splited[length-(length-count)] == 'm'):
        product.append(CodeForAlpha['m'])
    elif(Sentence_splited[length-(length-count)] == 'n'):
        product.append(CodeForAlpha['n'])
    elif(Sentence_splited[length-(length-count)] == 'o'):
        product.append(CodeForAlpha['o'])
    elif(Sentence_splited[length-(length-count)] == 'p'):
        product.append(CodeForAlpha['p'])
    elif(Sentence_splited[length-(length-count)] == 'q'):
        product.append(CodeForAlpha['q'])
    elif(Sentence_splited[length-(length-count)] == 'r'):
        product.append(CodeForAlpha['r'])
    elif(Sentence_splited[length-(length-count)] == 's'):
        product.append(CodeForAlpha['s'])
    elif(Sentence_splited[length-(length-count)] == 't'):
        product.append(CodeForAlpha['t'])
    elif(Sentence_splited[length-(length-count)] == 'u'):
        product.append(CodeForAlpha['u'])
    elif(Sentence_splited[length-(length-count)] == 'v'):
        product.append(CodeForAlpha['v'])
    elif(Sentence_splited[length-(length-count)] == 'w'):
        product.append(CodeForAlpha['w'])
    elif(Sentence_splited[length-(length-count)] == 'x'):
        product.append(CodeForAlpha['x'])
    elif(Sentence_splited[length-(length-count)] == 'y'):
        product.append(CodeForAlpha['y'])
    elif(Sentence_splited[length-(length-count)] == 'z'):
        product.append(CodeForAlpha['z'])
    elif(Sentence_splited[length-(length-count)] == ' '):
        product.append(CodeForAlpha[' '])

then you'll initialize files correctly without any circular dependencies with each other.

CodePudding user response:

Make your main loop:

product = []
for c in Sentence_splited:
    product.append( Check_For_Alphas(c))
print(*product)

And replace the entire Check.py with this:

from MorseCode import *

def Check_For_Alphas(ch):
    if ch in CodeForAlpha:
        return CodeForAlpha[ch]
    return 'xxx'

CodePudding user response:

Do you really need all the imports? Be careful not to import in a loop, if you do.

Consider this single-file solution, especially the morse_encode function. You do not need all those checks, as you already have the dictionary set up.

from typing import List


CodeForAlpha = {
    "a": "._",
    "b": "_...",
    "c": "_._.",
    "d": "_..",
    "e": ".",
    "f": ".._.",
    "h": "....",
    "i": "..",
    "j": "._ _ _",
    "k": "_._",
    "l": "._..",
    "m": "_ _",
    "n": "_.",
    "o": "_ _ _",
    "p": "._ _.",
    "q": "_ _._",
    "r": "._.",
    "s": "...",
    "t": "_",
    "u": ".._",
    "v": "..._",
    "w": "._ _",
    "x": "_.._",
    "y": "_._ _",
    "z": "_ _..",
    " ": " "
}


def validate_input(s: str) -> bool:
    l = s.split()
    for w in l:
        if not w.isalpha():
            return False
    return True


def get_user_input() -> str:
    while True:
        text = input("Enter the text:\n")
        if validate_input(text):
            break
        else:
            print("Invalid input, only alphabetic characters and spaces are allowd.")
            print("Try again, please!")
    return text


def morse_encode(text: str) -> List[str]:
    result = list()
    for char in text.lower():
        result.add(CodeForAlpha[char])
    return result


"""
Less verbose version:
def morse_encode(text: str) -> List[str]:
    return [CodeForAlpha[char] for char in text.lower()]
"""


if __name__ == '__main__':
    user_text = get_user_input()
    morse_code_list = morse_encode(user_text)
    print(morse_code_list)
  • Related