Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7984357
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T11:14:43+00:00 2026-06-04T11:14:43+00:00

class Tasks(object): def __init__(self, container=None): if container is None: container = [] self.container =

  • 0
class Tasks(object):
    def __init__(self, container=None):
        if container is None:
            container = []
        self.container = container


    def add(self,name,date,priority):
        self.container.append([name,date,priority])

    def __str__(self):
        return str(self.container)

    def __repr__(self):
        return str(self.container)

    def __getitem__(self, key):
        return Tasks(self.container[key])

    def __len__(self):
        return len(self.container)


class management(Tasks):
    def save(self):
        outfile = open ("tasks.txt","w")
        outfile.write(("\n".join(map(lambda x: str(x), task))))

        print task
        outfile.close ()
    def load(self):
        load_file = open("tasks.txt","r")
        task = load_file.readlines()
        print task
        #this line is the attempt to convert back into the original format
        Tasks(add(task))




task = Tasks()        
if __name__== "__main__":

    p = management(Tasks)

    #task.add("birthday","27092012","high")
    #task.add("christmas","20062000","medium")
    #task.add("easter","26011992","low")
    print task

    #print len(task)
    #p.save()
    p.load()


    print "test",task
    print len(task)

the ultimate aim of my code is to generate a task manager(to do list)

the code above generates a list of [name,date,priority], it then saves it in a text file called tasks.txt – as far as im aware this works perfectly(as long as i comment out p.load).

however… the load function loads the file but I need to be able to print the list it loads as print task as I did when I had commented out p.load().

this will enable me to be able to eventually, delete,sort etc. tasks

thanks in advance

I apologise for the bad question I didn’t know how to word it on1 line

edit:
I thought about pickling which would preserve the list format, but i dont think it would solve my problem of being able to pass the arguments back into the Tasks() class in order to be able to print them as print task

edit 2
the load function now reads

 def load(self):
     with open("tasks.txt", "r") as load_file:
         tasks = [ast.literal_eval(ln) for ln in load_file]
     print tasks
     for t in tasks:
         todo.add(t)

obviously (or at least I think ) I get the error NameError: global name ‘todo’ is not defined
I have tried with task.add(t) and get TypeError: add() takes exactly 4 arguments (2 given)

I also tried with Tasks.add(t) and got the error TypeError: unbound method add() must be called with Tasks instance as first argument (got list instance instead)

I clearly dont understand the code, could you clarify, thanks.

edit 3
while True:
menu_choice = int(input(“Select a number from the menu”))

try:
    if menu_choice == 1:

        task = raw_input ("task")
        date = raw_input ("date")
        priority = raw_input ("priority")
        tasks = Tasks([(task,date,priority)])
        print tasks


    elif menu_choice == 2:
        print tasks
    elif menu_choice == 3:
        tasks.save()
    elif menu_choice == 4:
        tasks.load()
except:
    print sys.exc_info()

this over writes the task each time instead of appending it, any ideas? also menu choice 2,3,4 dont work because tasks isnt defined globally, not sure how I can get round this? maybe returning?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T11:14:45+00:00Added an answer on June 4, 2026 at 11:14 am

    Trying a different, more Pythonic approach. Not so much an answer, but more an alternative. Edited thrice to take into account a number of requests for new features.

    import pickle
    
    class TasksError(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
    
    class Task(object):
        def __init__(self, task = () ):
            if task ==():
                raise TasksError('Empty task.')
            self.name = task[0]
            self.date = task[1]
            self.priority = task[2]
    
        def __str__(self):
            output = '''Name: %s
    Date: %s
    Priority: %s
    ''' % ( self.name,
            self.date,
            self.priority )
            return output
    
    class Tasks(object):
        def __init__(self, container = []):
            self.container = [ Task(todo) for todo in container ]
    
        def find_by_priority(self, priority = 'high'):
            # example method to seek and print high priority tasks
            # using this example, you will be able to conduct many
            # types of searches
            results = [ task
                       for task in self.container
                       if task.priority == priority ]
            return results
    
        def sort_by_date(self):
            # example method of how to sort, again, many other
            # ways of sorting can be implemented, this is just
            # to demonstrate the principle
            # for more info on sorting,
            # visit:  http://wiki.python.org/moin/HowTo/Sorting
            self.container = sorted(self.container,
                                    key=lambda task: task.date)
    
        def add(self, task):
            if task == '':
                raise TasksError('Empty task')
            self.container.append( Task(task) )
    
        def save(self):
            try:
                output = open('tasks.pkl', 'wb')
                pickle.dump(self.container, output)
                output.close()
            except:
                raise TasksError('Failed to save.')
    
        def load(self):
            try:
                pkl_file = open('tasks.pkl', 'rb')
                self.container = pickle.load(pkl_file)
                pkl_file.close()
            except:
                raise TasksError('Failed to load')
    
        def __str__(self):
            output = '\n'.join( [ str(todo) for todo in self.container ] )
            return output
    
    if __name__== "__main__":
        divider = '-' * 30 + '\n'
    
        tasks = Tasks( [("birthday","20121111","high"),
                        ("christmas","20121225","medium"),
                        ("easter","20120405","low")] )
        print 'Three original tasks:\n'
        print tasks # prints out three tasks
        print divider
    
        tasks.add( ("new-task","20120320","high") )
        print 'Three original plus one new task:\n'
        print tasks # prints out four tasks
        print divider
    
        tasks.save() # pickles the task list and saves to disk
    
        tasks = Tasks( container = [] ) # creates a new, empty task list
        print 'Empty task list:\n'
        print tasks # prints out empty list
        print divider
    
        tasks.load() # loads the pickled list
        print 'The four pickled tasks, reloaded:\n'
        print tasks # prints out four tasks
        print divider
    
        while True:
            print divider, '''Make your selection:
    1. Add new task
    2. Print all tasks
    3. Save tasks
    4. Load tasks from disk
    5. Find high priority tasks
    6. Sort by date
    <ENTER> to quit
    '''
            try:
                menu_choice = int(input("Select a number from the menu: "))
            except:
                print 'Goodbye!'
                break
    
            if menu_choice == 1:
                # note: no error checking here
                # even an empty input is accepted
                task = raw_input (">>> Task: ")
                date = raw_input (">>> Date as string YYYYMMDD: ")
                priority = raw_input (">>> Priority: ")
                todo = (task, date, priority)
                # note that here you should add a task
                # your method created a NEW task list
                # and replaced the old one
                tasks.add( todo )
                print tasks
            elif menu_choice == 2:
                print divider, 'Printing all tasks'
                print tasks
            elif menu_choice == 3:
                print divider, 'Saving all tasks'
                tasks.save()
            elif menu_choice == 4:
                print divider, 'Loading tasks from disk'
                tasks.load()
            elif menu_choice == 5:
                print divider, 'Finding tasks by priority'
                results = tasks.find_by_priority(priority='high')
                for result in results: print result
            elif menu_choice == 6:
                print divider, 'Sorting by date'
                tasks.sort_by_date()
                print tasks
    

    IMPORTANT NOTE: This is code produced as an exercise to demonstrate many of the features that you are seeking to implement and to show how a proper use of object oriented design allows you to encapsulate each task and task-list and to manipulate them with ease. It also demonstrates the use of pickle as a Pythonic alternative to the text file implementation that you were using in the original question. It also demonstrates searching and sorting by field, implementing two simple methods.

    If you are serious about this project, you need to look at a proper database such as SQLite that will allow man more features for searching, sorting, updating, adding, and deleting records than you could reliably implement by hand.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have following codes in python2.x: class _CHAIN(object): def __init__(self, execution_context=None): self.execution_context = execution_context
import pickle class TasksError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
I have code like the following, class _Process(multiprocessing.Process): STOP = multiprocessing.Manager().Event() def __init__(self, queue,
from celery.task import Task class Decayer(Task): def calc_decay_value(self, x): y = (1.0/(2^x)) return y
Use case: class MyTask(Task): queue = 'default_queue' def run(self): # do work Normally I
What is difference when I do class T def initialize self.class.class_eval do def test
I have multiple Users, each with a collection of Tasks. public class User {
In Groovy code something simple: #!/usr/bin/env groovy public class test { boolean val def
This is related to . I'm trying to dynamically add the maven-ant-tasks jars with
In my models.py: from django.db import models from core import tasks class Image(models.Model): image

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.