This is to test the class; however, I am getting an error and I do not know how to fix it.
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'"""
def test_first_last_name(self):
"""Do names like 'Mark James' work?"""
formatted_name = get_formatted_name('mark','James')
self.assertEqual(formatted_name,'Mark James')
unittest.main()
Here's the class that is being tested.
def get_formatted_name(first, last):
"""This is where the name is formatted correctly"""
full_name = first + " " + last
return full_name.title()
The error I am getting is this:
/Desktop/python_work/test_name_function.py", line 1, in <module>
import unittest
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/__init__.py", line 58, in <module>
from .result import TestResult
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/result.py", line 5, in <module>
import traceback
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/traceback.py", line 3, in <module>
import linecache
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/linecache.py", line 10, in <module>
import tokenize
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tokenize.py", line 96, in <module>
class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
AttributeError: 'module' object has no attribute 'namedtuple'
Anyone have a clue?
I believe you need to add if 'name' == 'main':
unittest.main() to your code.
The below code should fix the error -
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'"""
def test_first_last_name(self):
"""Do names like 'Mark James' work?"""
formatted_name = get_formatted_name('mark','James')
self.assertEqual(formatted_name,'Mark James')
if '__name__' == '__main__':
unittest.main()
Related
I have a series of Python modules. Each one contains a class with a name matching its directory:
a/__init__.py
a/aa/__init__.py
a/ab/__init__.py
b/ba/__init__.py
b/bb/__init__.py
c/ca/__init__.py
c/ca/caa/__init__.py
utils/__init__.py
I have a free variable and function that maps the class in each module to a string, in utils/__init__.py:
import a
import a.aa
import a.ab
import b
import b.ba
import b.bb
import c
import c.ca
import c.ca.caa
MAPPING = {
"Foobar": a.A,
"Apple": a.aa.Aa,
"Banana": a.ab.Ab,
"Clementine": b.ba.Ba,
"Granola": b.B,
"Donut": b.bb.Bb,
"Hashbrowns": c.C,
"Egg": c.ca.Ca,
"Furniture": c.ca.caa.Caa,
}
def find_class(s):
return MAPPING[s]
However, I would like to use this function inside some of these classes. For example, b/ba/__init__.py may contain the following:
import utils
class Ba():
def mycall(self, s):
return utils.find_class(s)
This causes an issue trying to import that class:
Python 3.9.6 (default, Jun 29 2021, 05:25:02)
>>> from b.ba import Ba
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../python3imports/b/ba/__init__.py", line 1, in <module>
import utils
File ".../python3imports/utils/__init__.py", line 15, in <module>
"Clementine": b.ba.Ba,
AttributeError: module 'b' has no attribute 'ba'
>>>
Is there a way to have a "master list" of classes, and use that list within those classes?
It's a little hacky but this solution is functional:
MAPPING = {}
def _make_mapping(m):
import a
import a.aa
import a.ab
import b
import b.ba
import b.bb
import c
import c.ca
import c.ca.caa
m["Foobar"] = a.A
m["Apple"] = a.aa.Aa
m["Banana"] = a.ab.Ab
m["Clementine"] = b.ba.Ba
m["Granola"] = b.B
m["Donut"] = b.bb.Bb
m["Hashbrowns"] = c.C
m["Egg"] = c.ca.Ca
m["Furniture"] = c.ca.caa.Caa
def find_class(s):
if not MAPPING:
_make_mapping(MAPPING)
return MAPPING[s]
This prevents any class imports from being attempted until find_class is run for the first time, determines that MAPPING is empty, and populates it. In this way, importing utils in one of the listed classes keeps a circular import from occurring.
I have used the following link for JavaScript grammar .
https://github.com/antlr/grammars-v4/tree/master/javascript/javascript/Python
i have used antlr4.8 and ntlr4-python3-runtime==4.8. when i use the following code it gives following error .
error:
PS N:\antlr4\sample\py4.8> python main.py test.js
Running
Test started for: test.js
Created parsers
Traceback (most recent call last):
File "main.py", line 25, in <module>
main(sys.argv)
File "main.py", line 20, in main
tree = parser.program()
File "N:\antlr4\sample\py4.8\JavaScriptParser.py", line 880, in program
self.enterRule(localctx, 0, self.RULE_program)
File "C:\Users\root\AppData\Local\Programs\Python\Python38\lib\site-packages\antlr4\Parser.py", line 366, in enterRule
self._ctx.start = self._input.LT(1)
.
.
.
File "N:\antlr4\sample\py4.8\JavaScriptLexer.py", line 919, in sempred
return pred(localctx, predIndex)
File "N:\antlr4\sample\py4.8\JavaScriptLexer.py", line 925, in HashBangLine_sempred
return this.IsStartOfFile()
NameError: name 'this' is not defined
code:
import sys
from antlr4 import *
import JavaScriptLexer
import JavaScriptParser
JSL = JavaScriptLexer.JavaScriptLexer
JSP = JavaScriptParser.JavaScriptParser
class WriteTreeListener(ParseTreeListener):
def visitTerminal(self, node:TerminalNode):
print ("Visit Terminal: " + str(node) + " - " + repr(node))
def main(argv):
input_stream = FileStream(argv[1])
print("Test started for: " + argv[1])
lexer = JSL(input_stream)
stream = CommonTokenStream(lexer)
parser = JSP(stream)
print("Created parsers")
tree = parser.program()
ParseTreeWalker.DEFAULT.walk(WriteTreeListener(), tree)
if __name__ == '__main__':
print("Running")
main(sys.argv)
print("Hello")
What have I done wrong ?
Replace this with self
(ref here). Example:
Change
return this.IsStartOfFile()
to
return self.IsStartOfFile().
Run the script transformGrammar.py, as indicated in documentation.
I have a subclassed Course class as follows:
# course.py
class Course:
"""Represent a single Course"""
kind = 'Gen Ed'
def __init__(self, name, number) :
self._name = name # 'private' instance variable\
self._number = number
self.__display()
def display(self):
print(self.kind,"Course:" , self._name, self._number, sep=" ")
__display = display # private copy
class CSCourse(Course):
"""Represent a single CS Course"""
kind = 'CS' # class variable shared by all CSCourses
def __init__(self, name, number, language, numberOfPrograms):
Course.__init__(self, name, number)
self._language = language
self._numberOfPrograms = numberOfPrograms
def display(self):
Course.display(self)
print('Language', self._language,
'Number Of programs:', self._numberOfPrograms, sep = ' ')
I import the module as follows:
>>>from course import *
This does not throw any exception, but then when I issue the following to call the constructor, I get the error below?
>>> cs360=CSCourse("Special Topics", 360, "python", 21)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'CSCourse' is not defined
What am I doing wrong please? I did also try to see what methods are available in the classes imported. It seems nothing is being imported!
>>> import inspect
>>> inspect.getmembers(Course, lambda a:not(inspect.isroutine(a)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Course' is not defined
>>> inspect.getmembers(CSCourse, lambda a:not(inspect.isroutine(a)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'CSCourse' is not defined
For anyone else having this problem, check if you have circular imports (in file a.py from b import * and in file b.py from a import *). Python doesn't seem to raise an exception when that happens, but the import doesn't work. Restructuring the code to remove the circular import fixed the problem for me.
I installed corpcrawl but when I try to run this code from its documentation page:
from corpcrawl.crawler import CorpCrawl
from corpcrawl.backend import Backend
def main()
I get the following error
from corpcrawl.crawler import CorpCrawl
Traceback (most recent call last):
File "<ipython-input-40-a34fa6bf09cd>", line 1, in <module>
from corpcrawl.crawler import CorpCrawl
File "C:\ProgramData\Anaconda3\lib\site-packages\corpcrawl\crawler.py", line 1, in <module>
from parser import Parser
ImportError: cannot import name 'Parser'
def main()
File "<ipython-input-44-eaaf015e0d6b>", line 1
def main()
^
SyntaxError: invalid syntax
Why am I getting this error?
The code from corpcrawl's documentation page is broken:
Missing :
Wrong indentation
Illegal characters (such as “ instead of ")
Here is what it should look like (Python 2):
from corpcrawl.crawler import CorpCrawl
from corpcrawl.backend import Backend
class MyBackend(Backend):
def get_company(self, name):
pass
def add_company(self, comp):
print "Adding %s" % str(comp)
def main():
my_backend = MyBackend()
crawler = CorpCrawl(cache_path = '/an/absolute/path/to/some/dir', backend = my_backend)
c.crawl(years = [2011, 2012], quarters = [1, 2, 3, 4])
I know there're already many people who asked this questions look like this but I really can't find a solution which works for me.
In ex48. I write the "lexicon.py" and nosetests it.but it reports an error:
Traceback (most recent call last):
File "c:\python27\lib\site-packages\nose\case.py", line 197, in runTest
self.test(*self.arg)
File "D:\pyhomework\ex48\skeleton\tests\lexicon_tests.py", line 31, in test_errors
assert_equal(Lexicon.scan("ASDFASDF"),[('errors','ASDFASDF')])
AttributeError: 'module' object has no attribute 'scan'
this is lexicon.py:
class Lexicon(object):
def __init__(self):
self.dic = {'direction':('north','south','east'),
'verb':('go','kill','eat'),
'stop':('the','in','of'),
'noun':('bear','princess'),
'number':('1234','3','91234'),
'error':('ASDFASDF','IAS')}
def scan(self,words):
self.word = words.split()
self.result = []
for item in self.word:
for key,value in self.dic.items():
if item in value:
self.result.append((key,item))
return self.result
this is lexicon_tests.py
from nose.tools import *
from ex48 import Lexicon
def test_direction():
assert_equal(Lexicon.scan("north"),[('direction','north')])
result = Lexicon.scan("north south east")
assert_equal(result,[('direction','north'),('direction','south'),('direction','east')])
def test_verbs():
assert_equal(Lexicon.scan("go"),[('verb','go')])
result = Lexicon.scan("go kill eat")
assert_equal(result,[('verb','go'),('verb','kill'),('verb','eat')])
def test_stops():
assert_equal(Lexicon.scan("the"),[('stop','the')])
result = Lexicon.scan("the in of")
assert_equal(result,[('stop','the'),('stop','in'),('stop','of')])
def test_nouns():
assert_equal(Lexicon.scan("bear"),[('noun','bear')])
result = Lexicon.scan("bear princess")
assert_equal(result,[('noun','bear'),('noun','princess')])
def test_numbers():
assert_equal(Lexicon.scan("1234"),[('number','1234')])
result = Lexicon.scan("3 91234")
assert_equal(result,[('number','3'),('number','91234')])
def test_errors():
assert_equal(Lexicon.scan("ASDFASDF"),[('errors','ASDFASDF')])
result = Lexicon.scan("bear IAS princess")
assert_equal(result,[('noun','bear')('error','IAS')('noun','princess')])
this is the skeleton:
-bin
-docs
-ex48 (-__init__.py -Lexicon.py)
-tests (-__init__.py -lexicon_tests.py)
-setup
I have tried several ways but still get the same error.
thank you for any advice.
When you write from ex48 import Lexicon what is imported is the Lexicon.py file as a python module. Yet, this module contains a Lexicon class, which contains the method you want to use.
To get rid of your error, try this import statement : from ex48.lexicon import Lexicon this way you will use the Lexicon object that is defined in the lexicon.py file.
from ex48 import Lexicon
So you imported the module lexicon.py.
In your module lexicon.py you have a class Lexicon.
So to call methods of the class Lexicon you have to use notation
Lexicon.Lexicon.method()