Python Forum

Full Version: Use variable from one function in another without return
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm having those two functions in my code and want to be able to use the variable tdate from the function def todos_new(): in my second function def todos_print():.

def todos_new():
    tid = 139283983
    ttext = "text"
    tdate = "2018-12-12"
    new = tclass.ToDo(tid, ttext, tdate)
    todos.append(new)

def todos_print():
    datesearch = input('Search Date YYYY-MM-DD:')
    if datesearch < todos(tdate):#NameError: name 'tdate' is not defined
        print(todos)
Any idea how I can use that variable in my second function without return in my first function?
Thanks for your input!
Either use global variable or use class.
Sorry, didn't post the code from the class before - I use the following:

class.py
class tclass:
    def __init__(self, tid, ttext, tdate):
            self.tid = tid
            self.ttext = ttext
            self.tdate = tdate
main.py
import tclass
todos =[]

def todos_new():
    tid = 139283983
    ttext = "text"
    tdate = "2018-12-12"
    new = tclass.ToDo(tid, ttext, tdate)
    todos.append(new)

def todos_print():
    datesearch = input('Search Date YYYY-MM-DD:')
    if datesearch < todos(tdate):
        print(todos)
Still get the NameError: name 'tdate' is not defined. Any idea? Thanks!
To implement these with the class, the functions need to be methods of the class and todos_print() will need to use self.tdate. From what I'm seeing, it appears that you intend to make a list of todo items. In that case, you should have a second class to contain and manage that list. Something like this:

class Todo_list:
    todos = []

    def add_todo_item(self, todo):
        if isinstance(todo, tclass):
            self.todos.append(todo)

    def print_todo_list(self):
        print(self.todos)