Basic to-do CLI app (with JSON for persistence) using Python

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite
1












I’m very new to Python. I wanted to start out with a simple project: a CLI app that keeps track of my to-do’s.



The code works as intended, but is what I have written is any good?



File structure:




  • task.py defines the task class


  • task_handler.py defines a class that helps retrieve/store the tasks


  • command.py ties everything together and processes the command

Files:



task.py



class Task:

def __init__(self, description):
self.description = description
self.completed = False

def complete(self):
self.completed = True


task_handler.py



import json
from task import Task


class TaskHandler:

def __init__(self, path):
self.path = path
self.stored_attributes = ['description', 'completed']

def store(self, tasks):
data =
for task in tasks:
obj =
for attr in self.stored_attributes:
obj[attr] = getattr(task, attr, None)
data.append(obj)

with open(self.path, 'w') as data_file:
json.dump(data, data_file)

def retrieve(self):
data =
try:
with open(self.path, 'r') as data_file:
data = json.load(data_file)
except FileNotFoundError:
pass

tasks =
for task in data:
obj = Task(task['description'])
for attr in self.stored_attributes:
setattr(obj, attr, task[attr])
tasks.append(obj)
return tasks


command.py



import os
import sys
import argparse
from task import Task
from task_handler import TaskHandler


def parse_args(args):
parser = argparse.ArgumentParser()
action_parser = parser.add_subparsers(title='actions', dest='action')

action_parser.add_parser('list')

add_action_parser = action_parser.add_parser('add')
add_action_parser.add_argument('description')

complete_action_parser = action_parser.add_parser('complete')
complete_action_parser.add_argument('index', type=int)

purge_action_parser = action_parser.add_parser('purge')
purge_action_parser.add_argument('index', type=int)

return parser.parse_args(args)


def main():
args = parse_args(sys.argv[1:])
task_handler = TaskHandler(os.path.expanduser('~') + '/.todo.json')
stored_tasks = task_handler.retrieve()

if args.action == 'add':
new_task = Task(args.description)
stored_tasks.append(new_task)
task_handler.store(stored_tasks)
print('Task added')
elif args.action == 'complete':
try:
stored_tasks[args.index].complete()
task_handler.store(stored_tasks)
print('Task marked as completed')
except IndexError:
print('No task with that index')
elif args.action == 'purge':
try:
del stored_tasks[args.index]
task_handler.store(stored_tasks)
print('Task purged')
except IndexError:
print('No task with that index')
else:
if not stored_tasks:
print('To-do list is empty')
else:
print('To-do:')
for idx, task in enumerate(stored_tasks):
completed = ' (completed)' if task.completed else ''
print('[] '.format(idx, task.description, completed))


if __name__ == '__main__':
main()


Any input would be highly appreciated! I want to focus on becoming a better programmer in any way I can.







share|improve this question



























    up vote
    2
    down vote

    favorite
    1












    I’m very new to Python. I wanted to start out with a simple project: a CLI app that keeps track of my to-do’s.



    The code works as intended, but is what I have written is any good?



    File structure:




    • task.py defines the task class


    • task_handler.py defines a class that helps retrieve/store the tasks


    • command.py ties everything together and processes the command

    Files:



    task.py



    class Task:

    def __init__(self, description):
    self.description = description
    self.completed = False

    def complete(self):
    self.completed = True


    task_handler.py



    import json
    from task import Task


    class TaskHandler:

    def __init__(self, path):
    self.path = path
    self.stored_attributes = ['description', 'completed']

    def store(self, tasks):
    data =
    for task in tasks:
    obj =
    for attr in self.stored_attributes:
    obj[attr] = getattr(task, attr, None)
    data.append(obj)

    with open(self.path, 'w') as data_file:
    json.dump(data, data_file)

    def retrieve(self):
    data =
    try:
    with open(self.path, 'r') as data_file:
    data = json.load(data_file)
    except FileNotFoundError:
    pass

    tasks =
    for task in data:
    obj = Task(task['description'])
    for attr in self.stored_attributes:
    setattr(obj, attr, task[attr])
    tasks.append(obj)
    return tasks


    command.py



    import os
    import sys
    import argparse
    from task import Task
    from task_handler import TaskHandler


    def parse_args(args):
    parser = argparse.ArgumentParser()
    action_parser = parser.add_subparsers(title='actions', dest='action')

    action_parser.add_parser('list')

    add_action_parser = action_parser.add_parser('add')
    add_action_parser.add_argument('description')

    complete_action_parser = action_parser.add_parser('complete')
    complete_action_parser.add_argument('index', type=int)

    purge_action_parser = action_parser.add_parser('purge')
    purge_action_parser.add_argument('index', type=int)

    return parser.parse_args(args)


    def main():
    args = parse_args(sys.argv[1:])
    task_handler = TaskHandler(os.path.expanduser('~') + '/.todo.json')
    stored_tasks = task_handler.retrieve()

    if args.action == 'add':
    new_task = Task(args.description)
    stored_tasks.append(new_task)
    task_handler.store(stored_tasks)
    print('Task added')
    elif args.action == 'complete':
    try:
    stored_tasks[args.index].complete()
    task_handler.store(stored_tasks)
    print('Task marked as completed')
    except IndexError:
    print('No task with that index')
    elif args.action == 'purge':
    try:
    del stored_tasks[args.index]
    task_handler.store(stored_tasks)
    print('Task purged')
    except IndexError:
    print('No task with that index')
    else:
    if not stored_tasks:
    print('To-do list is empty')
    else:
    print('To-do:')
    for idx, task in enumerate(stored_tasks):
    completed = ' (completed)' if task.completed else ''
    print('[] '.format(idx, task.description, completed))


    if __name__ == '__main__':
    main()


    Any input would be highly appreciated! I want to focus on becoming a better programmer in any way I can.







    share|improve this question























      up vote
      2
      down vote

      favorite
      1









      up vote
      2
      down vote

      favorite
      1






      1





      I’m very new to Python. I wanted to start out with a simple project: a CLI app that keeps track of my to-do’s.



      The code works as intended, but is what I have written is any good?



      File structure:




      • task.py defines the task class


      • task_handler.py defines a class that helps retrieve/store the tasks


      • command.py ties everything together and processes the command

      Files:



      task.py



      class Task:

      def __init__(self, description):
      self.description = description
      self.completed = False

      def complete(self):
      self.completed = True


      task_handler.py



      import json
      from task import Task


      class TaskHandler:

      def __init__(self, path):
      self.path = path
      self.stored_attributes = ['description', 'completed']

      def store(self, tasks):
      data =
      for task in tasks:
      obj =
      for attr in self.stored_attributes:
      obj[attr] = getattr(task, attr, None)
      data.append(obj)

      with open(self.path, 'w') as data_file:
      json.dump(data, data_file)

      def retrieve(self):
      data =
      try:
      with open(self.path, 'r') as data_file:
      data = json.load(data_file)
      except FileNotFoundError:
      pass

      tasks =
      for task in data:
      obj = Task(task['description'])
      for attr in self.stored_attributes:
      setattr(obj, attr, task[attr])
      tasks.append(obj)
      return tasks


      command.py



      import os
      import sys
      import argparse
      from task import Task
      from task_handler import TaskHandler


      def parse_args(args):
      parser = argparse.ArgumentParser()
      action_parser = parser.add_subparsers(title='actions', dest='action')

      action_parser.add_parser('list')

      add_action_parser = action_parser.add_parser('add')
      add_action_parser.add_argument('description')

      complete_action_parser = action_parser.add_parser('complete')
      complete_action_parser.add_argument('index', type=int)

      purge_action_parser = action_parser.add_parser('purge')
      purge_action_parser.add_argument('index', type=int)

      return parser.parse_args(args)


      def main():
      args = parse_args(sys.argv[1:])
      task_handler = TaskHandler(os.path.expanduser('~') + '/.todo.json')
      stored_tasks = task_handler.retrieve()

      if args.action == 'add':
      new_task = Task(args.description)
      stored_tasks.append(new_task)
      task_handler.store(stored_tasks)
      print('Task added')
      elif args.action == 'complete':
      try:
      stored_tasks[args.index].complete()
      task_handler.store(stored_tasks)
      print('Task marked as completed')
      except IndexError:
      print('No task with that index')
      elif args.action == 'purge':
      try:
      del stored_tasks[args.index]
      task_handler.store(stored_tasks)
      print('Task purged')
      except IndexError:
      print('No task with that index')
      else:
      if not stored_tasks:
      print('To-do list is empty')
      else:
      print('To-do:')
      for idx, task in enumerate(stored_tasks):
      completed = ' (completed)' if task.completed else ''
      print('[] '.format(idx, task.description, completed))


      if __name__ == '__main__':
      main()


      Any input would be highly appreciated! I want to focus on becoming a better programmer in any way I can.







      share|improve this question













      I’m very new to Python. I wanted to start out with a simple project: a CLI app that keeps track of my to-do’s.



      The code works as intended, but is what I have written is any good?



      File structure:




      • task.py defines the task class


      • task_handler.py defines a class that helps retrieve/store the tasks


      • command.py ties everything together and processes the command

      Files:



      task.py



      class Task:

      def __init__(self, description):
      self.description = description
      self.completed = False

      def complete(self):
      self.completed = True


      task_handler.py



      import json
      from task import Task


      class TaskHandler:

      def __init__(self, path):
      self.path = path
      self.stored_attributes = ['description', 'completed']

      def store(self, tasks):
      data =
      for task in tasks:
      obj =
      for attr in self.stored_attributes:
      obj[attr] = getattr(task, attr, None)
      data.append(obj)

      with open(self.path, 'w') as data_file:
      json.dump(data, data_file)

      def retrieve(self):
      data =
      try:
      with open(self.path, 'r') as data_file:
      data = json.load(data_file)
      except FileNotFoundError:
      pass

      tasks =
      for task in data:
      obj = Task(task['description'])
      for attr in self.stored_attributes:
      setattr(obj, attr, task[attr])
      tasks.append(obj)
      return tasks


      command.py



      import os
      import sys
      import argparse
      from task import Task
      from task_handler import TaskHandler


      def parse_args(args):
      parser = argparse.ArgumentParser()
      action_parser = parser.add_subparsers(title='actions', dest='action')

      action_parser.add_parser('list')

      add_action_parser = action_parser.add_parser('add')
      add_action_parser.add_argument('description')

      complete_action_parser = action_parser.add_parser('complete')
      complete_action_parser.add_argument('index', type=int)

      purge_action_parser = action_parser.add_parser('purge')
      purge_action_parser.add_argument('index', type=int)

      return parser.parse_args(args)


      def main():
      args = parse_args(sys.argv[1:])
      task_handler = TaskHandler(os.path.expanduser('~') + '/.todo.json')
      stored_tasks = task_handler.retrieve()

      if args.action == 'add':
      new_task = Task(args.description)
      stored_tasks.append(new_task)
      task_handler.store(stored_tasks)
      print('Task added')
      elif args.action == 'complete':
      try:
      stored_tasks[args.index].complete()
      task_handler.store(stored_tasks)
      print('Task marked as completed')
      except IndexError:
      print('No task with that index')
      elif args.action == 'purge':
      try:
      del stored_tasks[args.index]
      task_handler.store(stored_tasks)
      print('Task purged')
      except IndexError:
      print('No task with that index')
      else:
      if not stored_tasks:
      print('To-do list is empty')
      else:
      print('To-do:')
      for idx, task in enumerate(stored_tasks):
      completed = ' (completed)' if task.completed else ''
      print('[] '.format(idx, task.description, completed))


      if __name__ == '__main__':
      main()


      Any input would be highly appreciated! I want to focus on becoming a better programmer in any way I can.









      share|improve this question












      share|improve this question




      share|improve this question








      edited Apr 3 at 19:22









      Sam Onela

      5,81961544




      5,81961544









      asked Apr 3 at 19:06









      VirtualRaccoon

      384




      384

























          active

          oldest

          votes











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f191190%2fbasic-to-do-cli-app-with-json-for-persistence-using-python%23new-answer', 'question_page');

          );

          Post as a guest



































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes










           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f191190%2fbasic-to-do-cli-app-with-json-for-persistence-using-python%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Chat program with C++ and SFML

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          Will my employers contract hold up in court?