NameError creating instance of imported class - python

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.

Related

NameError: name 'user_record' is not defined

I am running this code in Python 3.7.
record = ('Dave', 'dave#example.com', '773-555-1212', '847-555-1212')
name, email, *phone_numbers = user_record
Error:
Traceback (most recent call last):
File "C:\UsersPythonWizard\Desktop\Python\Python.py", line 2, in <module>
name, email, *phone_numbers = user_record
NameError: name 'user_record' is not defined
>>>
You defined the tuple as record, not user_record, so user_record is not defined. Change one variable to the other and you'll be good.

Can't call function inside function in exec() environment

I have some python (2.7) code using exec() :
import math
def some_function(a, b):
return a+b
safe_dict = { 'Sqrt': math.sqrt, 'Smurf': some_function, "__builtins__": None }
with open('my_file.py') as f:
exec(f.read(), safe_dict, {})
print('The End')
And "my_file.py" is:
print('in exec script')
print('sqrt(2) = %f' % Sqrt(2)) # Call to math.sqrt through name 'Sqrt' given in globals
print('3+4 = %d' % Smurf(3, 4)) # Call to some_function through name 'Smurf' given in globals
def my_func(x):
return Sqrt(2+x)
print("my_func: %f" % my_func(1)) # No problems
def my_func2(x, f):
return f(x-1)
print("my_func2: %f" % my_func2(5, my_func)) # No problems too
def my_func3(x):
return my_func(x-1) # Here, leads to a "NameError: global name 'my_func' is not defined" in the next line
print("my_func3: %f" % my_func3(5))
I don't understand why there is a NameError in my_func3 when it tries to call my_func.
Why my_func3 is not able to call my_func, even if previously defined ?
Is there a way to make it work (not with my_func defined in the main module) ?
edit
Error is:
Traceback (most recent call last):
File "main.py", line 9, in <module>
exec(f.read(), safe_dict, {})
File "<string>", line 16, in <module>
File "<string>", line 15, in my_func3
NameError: global name 'my_func' is not defined

Why can't I run the example code of the Python package corpcrawl?

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])

Python 3: Check if a string is an import command

I want to check a string - is it an import command? I have tried
# Helper - analyses a string - is it an import string?
"""
fromlike - from foo import bar
classic - import foo
classic_as - import foo as baz
"""
def check_is_import(string):
importname = ''
fromlike = False
classic = False
classic_as = False
if string[0:4] is 'from':
fromlike = True
importname = ''
if not fromlike and (string[0:6] is 'import'):
classic = True
importname = string.split(' ')[1]
if classic:
commandlist = string.split(' ')
if commandlist[2] is 'as':
classic_as = True
importname = commandlist[3]
del commandlist
if fromlike:
return ('fromlike', importname)
elif classic and (not classic_as):
return ('classic', importname)
elif classic_as:
return ('classic_as', importname)
else:
return ('no_import', importname)
but it worked for "fromlike" imports. (Note: I'm not asking "why does this code don't work?", I'm just searching a solution) What code will sure detect all imports? Basically my code takes a slice of the string. If the [0:4] slice equals 'from', the string is a "fromlike import". Else: if the [0:6] slice equals 'import', the string is a "classic import". If it detects 'as', it will find the pseudo-name. This function must return a tuple which contains the import type under index 0 and imported module-name under index 1.
If you want to be sure to handle all Python import forms, have Python do the parsing. Use the ast.parse() function and use the resulting parse tree; you'll either get Import or ImportFrom objects:
| Import(alias* names)
| ImportFrom(identifier? module, alias* names, int? level)
Each alias consists of a name and optional identifier used to import the name as:
-- import name with optional 'as' alias.
alias = (identifier name, identifier? asname)
Note that there can be multiple imports! You either have classic or fromlike imports, and both can import multiple names. Your function needs to return a list of (type, name) tuples. For invalid inputs, raise an exception (ValueError is a good fit here):
import ast
def check_is_import(string):
try:
body = ast.parse(string).body
except SyntaxError:
# not valid Python
raise ValueError('No import found')
if len(body) > 1:
# not a single statement
raise ValueError('Multiple statements found')
if not isinstance(body[0], (ast.Import, ast.ImportFrom)):
raise ValueError('No import found')
type_ = 'classic' if isinstance(body[0], ast.Import) else 'fromlike'
results = []
for alias in body[0].names:
alias_type = type_
if alias.asname:
alias_type += '_as'
results.append((alias_type, alias.asname or alias.name))
return results
The method should probably be renamed to extract_import_names(), as that reflects what it does much better.
Demo:
>>> check_is_import('from foo import bar')
[('fromlike', 'bar')]
>>> check_is_import('import foo')
[('classic', 'foo')]
>>> check_is_import('import foo as baz')
[('classic_as', 'baz')]
>>> check_is_import('from foo import bar, baz as spam, monty as python')
[('fromlike', 'bar'), ('fromlike_as', 'spam'), ('fromlike_as', 'python')]
>>> check_is_import('import foo as baz, baz, spam as ham')
[('classic_as', 'baz'), ('classic', 'baz'), ('classic_as', 'ham')]
>>> check_is_import('invalid python')
Traceback (most recent call last):
File "<stdin>", line 3, in check_is_import
File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
invalid python
^
SyntaxError: invalid syntax
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in check_is_import
ValueError: No import found
>>> check_is_import('import foo; import bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in check_is_import
ValueError: Multiple statements found
>>> check_is_import('1 + 1 == 2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in check_is_import
ValueError: No import found

python 2.7 def error

def h(x):
x = ((x[0])*len(x))
return x
when i print it, it goes
h(he)
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
h(he)
NameError: name 'he' is not defined
Do you maybe mean to pass he as a string? 'he' would be the appropriate way then.
def h(x):
x = ((x[0])*len(x))
return x
print(h('he'))
>>> hh

Categories

Resources