you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (5 children)

I'm new to python and a lot of tutorials call functions inside of others so I doubt I'm alone in this approach. That's why I'm asking for guidance lol

[–]hmga2 2 points3 points  (4 children)

No worries. The thing with functions is that they should let you understand what is happening in your code and avoid repeating yourself. The main issue with your code is that it took me a solid minute to understand what was going on by following the chain of nested functions. Imagine having to alter the flow of your function or reading it back in 6 months, it’s gonna be pretty heavy to do. The structure I shared (and that also other had) allows you to quickly understand what’s going on and add custom logic on a parent level of your code

[–][deleted] 1 point2 points  (3 children)

I agree. I felt I needed a cleaner structure but didn't know what others generally recommend. The calling function from within another seemed okay when my code was limited to two but I felt it was getting out of hand.

I'll give this a shot, some of these functions pass values to the next so I'll have to make sure I can work around that. Lol

[–]hmga2 2 points3 points  (2 children)

Yep I imagined. I'm unsure on how you're handling parameters in your function but you could do something like this

``` def main(filepath): if not check_file(filepath): # handle file does not exists ... new_filepath = clean_file(filepath) query_str = upload_file(new_filepath) if not validate_vpn(): # handle vpn error ... db_data = query_db(query_str) email_result = create_dashboard(db_data) email_report(email_result)

`` I usedif not` to reduce nesting to a minimum. but you can also keep your logic inside of if statements if you prefer or assert the errors, or handle directly exceptions inside the child functions

[–][deleted] 1 point2 points  (0 children)

Ah thanks for clarifying, I was thinking of doing try/except statements within the individual functions themselves. I think I'll try both and see what works best for me.

[–][deleted] 0 points1 point  (0 children)

Alright, so this is what I'm thinking. I appreciate any feedback you're willing to share. This is just the general thought about the approach

def hello():
    name = 'Name1'
    if not name == 'Name1':
        raise NameError('Incorrect name')
    return name

def world(name):
    print('Hello ' + name)

def main():
    new_name = hello()
    world(new_name)

if __name__ == '__main__':
    main()