sevenwheels
sevenwheels

Reputation: 21

sys doesn't import properly when importing another module

I have been trying to import a custom module called 'nester' and this module uses sys.stdout. If I try to import nester I get an error. What is the issue here?

import sys 
import nester

x = ['a', 'b', 'c'] 
nester.print_lol(x)

This is the nester module

def print_lol(the_list, indent=False, level=0, fh=sys.stdout):
    for each_item in the_list:
        if isinstance(each_item, list):
            print_lol(each_item, indent, level+1, fh)
        else:
            if indent:
                for tab_stop in range(level):
                    print("\t", end='', file=fh)
            print(each_item, file=fh)

I was able to install the module locally without any errors but it still doesn't work. I've been trying to search for a solution for 2 hours with no luck so any help would be appreciated. I am following a tutorial by Head First Python from p. 126.

Upvotes: 0

Views: 410

Answers (1)

David Zwicker
David Zwicker

Reputation: 24298

You need to import sys in the submodule itself, such that the full source code reads

import sys

def print_lol(the_list, indent=False, level=0, fh=sys.stdout):
    for each_item in the_list:
        if isinstance(each_item, list):
            print_lol(each_item, indent, level+1, fh)
        else:
            if indent:
                for tab_stop in range(level):
                    print("\t", end='', file=fh)
            print(each_item, file=fh)

Note the added import on the first line.

Upvotes: 1

Related Questions