-1

NOTE: For anyone stumbling upon this thread, I highly recommend reading the article this post "duplicates". It goes into great detail why this issue is happening and lays out the design flaw of the language. TLDR; functions have elements that act like classes and will maintain data between calls, even though literally nothing in your code will tell it to do that....

The title pretty much explains it all. I can only call the definition processJSON it runs perfectly, but any/all other calls to it literally doesn't do anything and it's driving me crazy. Why does it not run anymore?

import json
import os
import csv
import copy

def processJSON(initialDict:dict, outPut:dict = {}, createTemplate:bool = False, parentKey:str = None, sep:str ='.', skipParent:bool = False) -> dict:

    #Loop through all keeys and return unique options
    for key in initialDict.keys():

        #Create needed variables
        keyTitle = str(parentKey + sep + key if parentKey else key)

        #Loop
        if type(initialDict[key]) == dict:
            parentTitle = ('' if skipParent else keyTitle)
            outPut.update(processJSON(initialDict=initialDict[key], outPut = outPut, createTemplate = createTemplate, parentKey = parentTitle, sep = sep))
        elif keyTitle not in outPut.keys():
            print(createTemplate)
            keyValue = str('' if createTemplate == True else initialDict[key])
            outPut[keyTitle] = keyValue

    return dict(outPut)
#Basic Veriables
scriptDirectory = os.path.dirname(os.path.realpath(__file__))

#Read the JSON files.
#Library File
with open(os.path.join(scriptDirectory,'inventoryItem.json'), "r",encoding='utf-8') as read_file:
    lib = json.load(read_file)

#English Dictionary
with open(os.path.join(scriptDirectory,'en.json'), "r",encoding='utf-8') as read_file:
    en = json.load(read_file)

for key in lib['inventoryItem'].keys():
    firstItem = True
    header =  processJSON(initialDict=lib['inventoryItem'][key], createTemplate=True, skipParent=True)

    try:
        with open(os.path.join(scriptDirectory,'export',f"{key}.csv"),"w", newline='', encoding='utf-8') as csvfile:

            for item in lib['inventoryItem'][key]:
                print(item)
                
                #Copy Header because Python sucks
                row = copy.deepcopy(header)
                print(processJSON(initialDict=lib['inventoryItem'][key][item], createTemplate=False, skipParent=False))
                row.update(processJSON(initialDict=lib['inventoryItem'][key][item], createTemplate=False, skipParent=False))
                print(row)
                break
                
                print(row)
                row.update(processJSON(initialDict=lib['inventoryItem'][key][item]))
                print(row)
                if firstItem:
                    firstItem = False
                    writer = csv.DictWriter(csvfile, fieldnames=header.keys(),delimiter = ';')
                    writer.writeheader()
                    
                writer.writerow(row)
                
    except IOError:
        print("I/O error")

    break
Nick W.
  • 1,536
  • 3
  • 24
  • 40
  • 1
    If you call a function, it will run. If the behavior you're expecting isn't happening, then the function isn't being called, or a logic error within the function is causing bad behavior. Have you confirmed that the function is being entered? – Carcigenicate Aug 15 '21 at 20:44
  • 1
    What *does* happen? How have you tried to debug the problem? If you put `print` statements in `processJSON`, can you confirm it's being called as expected? If you inspect the return value, does it match your expectations? – larsks Aug 15 '21 at 20:44
  • The code is pretty complex and in your last question with the same code, I asked why don't you use pandas which is going to make it simpler. I canot run your code, since I don't have the data, so I am going to assume that ` outPut:dict = {}` in your function definition is unsafe. It is better to set it to None and do outPut = outPut or {} inside the function – tchar Aug 15 '21 at 20:48
  • 1
    terminology note, you are talking about a *function*, not a "definition". – juanpa.arrivillaga Aug 15 '21 at 20:49
  • Side note: It would be nice if you respected the [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) concerning the naming of the variables. Your code is hard to read now. – Matthias Aug 15 '21 at 20:52
  • @tchar best I can tell that doesn't actually achieve the goal I am looking to achieve, but I moved this to a separate question because its a separate problem. I have finally figured this out and will close both questions now. Only took 2 miserable days lol. – Nick W. Aug 15 '21 at 23:35
  • @Matthias sorry, rewritten this about 200 times over the last day or so, this is just an easy to read format compared to PEP. If I ever move this to a public setting i'll convert it, I just find the PEP format miserable to deal with. – Nick W. Aug 15 '21 at 23:36

1 Answers1

1

Hard to run your code but you can try to:

Replace:

def processJSON(initialDict:dict, outPut:dict = {}, createTemplate:bool = False, parentKey:str = None, sep:str ='.', skipParent:bool = False) -> dict:

By: (remove outPut from args of your function)

def processJSON(initialDict:dict, createTemplate:bool = False, parentKey:str = None, sep:str ='.', skipParent:bool = False) -> dict:
    outPut = {}

With you actual code, you should try to print(outPut) at the beginning of your function. I think you could be surprised :-)

def processJSON(outPut={}):
    print(outPut)
    outPut['A'] = 1

print('First call')
processJSON()
print('Second call')
processJSON()
First call
{}
Second call
{'A': 1}
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • This makes literally 0 sense logically, but it works for some reason.... I am a pro at powershell, but some of these weird ass quirks with Python are driving my up a wall. There is so much awesome stuff Python can do but ugh lol. Python scoping and arguments seem like an absolute trainwreck.... – Nick W. Aug 15 '21 at 21:04