u/Advanced_Glass5563

python project structure - where do you store the data files (eg json data files)

Hi, I am building a simple class that parses dictionary data where the data themselves are stored on a dictionary.json file.

with open ('dictionary.json' , 'r') as file:
            self.game_lexicon = json.load(file)

Under which folder would you save this file on your python project?

Would you create a data folder ?

reddit.com
u/Advanced_Glass5563 — 1 day ago

How to use python unittest module to tests a custom Exception

Hi all

I' trying to understand a bit more about the python testing framework.

I have a small code on a parser.py file where there is a ParseError class defined and used on the parse_verb method of the Parser class

class ParseError(Exception):
    pass

class Parser(object):
    def __init__(self, word_list):
        self.word_list = word_list

    def skip(self, word_type):
        pass

    def match(self, expecting):
        pass
          
    def parse_verb(self):
        self.skip('stop')
        if self.peek() == 'verb':
            return self.match('verb')
        else:
            raise ParseError("Expected a verb next.")

I am trying to write a unit test for the parse_verb method using the below code

import unittest
from ex48 import lexicon
from ex48 import parser


class TestParser(unittest.TestCase):
        
    def test_parse_verb(self):
        my_parser = parser.Parser([('stop','the'),
                                ('noun','princess')])
        with self.assertRaises(ParseError):
            my_parser.parse_verb()

if __name__ == '__main__':
     unittest.main()

When I try to execute the test using command line

python -m unittest tests\tests_parser.py

I receive ErrorName failed message

NameError: name 'ParseError' is not defined. Did you mean: 'NameError'?

If instead of

with self.assertRaises(ParseError):
my_parser.parse_verb()

I use

with self.assertRaises(Exception):
            my_parser.parse_verb()

everything works fine. Any idea what the issue might be?

reddit.com
u/Advanced_Glass5563 — 3 days ago

Hi everyone,

While studying python I have the feeling it it not the most efficient programming language in terms of computing resource requirements.

In order to make sure I learn to code efficiently I'm using a Dell Inspiron from 2021 whose processes typically occupy 80-90% of RAM

I have created a very simple lexicon.py file with a class that builds a list of tuples based on a dictionary with multiple values per each key.

import time

class Lexicon:
def __init__(self):
self.list_tuples = []
self.game_lexicon = {
'direction': ['north', 'south', 'east', 'west' , 'down', 'up','left','right','back'],
'verb': ['go', 'stop','kill', 'eat'],
'stop': ['the', 'in', 'of', 'from', 'at', 'it'],
'nouns': ['door', 'bear', 'princess', 'cabinet'],
'number': [0,1,2,3,4,5,6,7,8,9]
}

for key in self.game_lexicon.keys():
values = self.game_lexicon.get(key)
for i in values:
self.list_tuples.append((key, i))

start_time = time.time()
print("--- %s seconds ---" % (time.time() - start_time))

print("Hi there! How are you today?")
print("Please let me know how can I help:")

lexicon = Lexicon()
print("--- %s seconds ---" % (time.time() - start_time))

When I execute the file I receive below stats:

python lexicon.py

--- 1.1920928955078125e-06 seconds ---

Hi there! How are you today?

Please let me know how can I help:

--- 0.008804082870483398 seconds ---

As you can see, it takes more than 1 second for the first print. Is this due to inefficiency on the code itself? More in general, is there a better, more efficient way to build the list of tuples than the one I have used?

reddit.com
u/Advanced_Glass5563 — 17 days ago

Hello , I'm fairly new to python and playing with some exercises provided Zed Shaw on his book "Learn python the hard way".

I was trying to repurpose for fun his game for my little nephews and I ended up creating a list which string elements are longer than 80 chars.

Eg

class Death(object):

quips = [

"Oh ... seems like Snow , your puppy, is better than you at this game. Retry with something better" ,

	*"Hopefully you are better at school than at this game",*

	*"Hmmm .... you better think of something smarter"*

]

def enter(self):

print( Death.quips[randint(0, len(self.quips) -1)])

exit(1)

As you might notice the first element of the list is longer than 80 chars. How can I manage this string in 2 rows both on the list declaration and on the print screen (command line) when the python code is executed ?

reddit.com
u/Advanced_Glass5563 — 24 days ago