python 2.7 def error - python

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

Related

why is 'log' object not callable?

x = Symbol ("x")
f = log(x)
dif1 = diff(f,x)
dif2 = diff(dif1,x)
dif3 = diff(dif2,x)
dif4 = diff(dif3,x)
dif5 = diff(dif4,x)
def D11(a,h):
return (f.evalf(subs={x:a+h})-f.evalf(subs={x:a}))/h + (h/2)*dif2.evalf(subs={x:a+h/2})
def D12(a,h):
return ((f.evalf(subs={x:(a+h)}) - f(a-h)))/(2*h) - h**2/6*dif3.evalf(subs={x:(a)})
def D13(a,h):
return (f.evalf(subs={x:(a-2*h)})- 8*f.evalf(subs={x:(a-h)}) + 8*f.evalf(a+h) - f(a+2*h))/(12*h) - h**4/30*ftuletis5(a)
def D22(a,h):
return (f.evalf(subs={x:(a+h)}) - 2*f.evalf(subs={x:(a)}) + f.evalf(subs={x:(a-h)}))/h**2 - h**2/12*(dif4.evalf(subs={x:(a)}))
vigaD11 = []
vigaD12 = []
vigaD13 = []
vigaD22 = []
h=[]
for i in range(20):
h+=h+[(10**(-i))]
vigaD11+= vigaD11 + [(D11(2,h[i])-(dif1.evalf(subs={x:2})))]
vigaD12+= vigaD12+[(D12(2,h[i])-(dif1.evalf(subs={x:2})))]
vigaD13+= vigaD13 + [(D13(2,h[i])-(dif1.evalf(subs={x:2})))]
vigaD22+= vigaD22 [(D22(2,h[i])-(dif2.evalf(subs={x:2})))]
I get an error message saying that log object is not callable. Currently I'm using the math package and Sympy package to get the program to do what I want.
The error message I get:
Traceback (most recent call last):
File "C:\Users\arman\Desktop\Numbrilised meetodid\praktikum12\praktikum12.py", line 64, in <module>
vigaD12+= vigaD12+[(D12(2,h[i])-(dif1.evalf(subs={x:2})))]
File "C:\Users\arman\Desktop\Numbrilised meetodid\praktikum12\praktikum12.py", line 37, in D12
return ((f.evalf(subs={x:(a+h)}) - f(a-h)))/(2*h) - h**2/6*dif3.evalf(subs={x:(a)})
TypeError: 'log' object is not callable
It still does not work when I specifically call out the sympy version of log. Please help.
You could try f = math.log(x) or whichever log function you want to use. Maybe python just doesn't find the right function to call.
In an isympy session with * import ofsympyandxsymbol,log` a sympy object
In [1]: log
Out[1]: log
In [2]: x
Out[2]: x
In [3]: f = log(x)
In [4]: f(23)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-a73e6f7d2549> in <module>
----> 1 f(23)
TypeError: 'log' object is not callable
You can't call log again; it's already been "called". You can evaluate it at specific number with:
In [13]: f.evalf(subs={x:1.23})
Out[13]: 0.207014169384326
You do that once in the problem expression, but not the second time. Why not?
f.evalf(subs={x:(a+h)}) - f(a-h)

NameError creating instance of imported class

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.

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 - ast - How to find first function

I'm trying to find the first function in arbitrary Python code.
What's the best way to do this?
Here's what I've tried so far.
import ast
import compiler.ast
code = """\
def func1():
return 1
def func2():
return 2
"""
tree = compiler.parse(code)
print list(ast.walk(tree))
But I'm getting an error I don't understand.
Traceback (most recent call last):
File "test.py", line 15, in <module>
print list(ast.walk(tree))
File "/usr/lib64/python2.7/ast.py", line 215, in walk
todo.extend(iter_child_nodes(node))
File "/usr/lib64/python2.7/ast.py", line 180, in iter_child_nodes
for name, field in iter_fields(node):
File "/usr/lib64/python2.7/ast.py", line 168, in iter_fields
for field in node._fields:
AttributeError: Module instance has no attribute '_fields'
Use ast.parse, not compiler.parse:
>>> import ast
>>>
>>> code = """
... def func1():
... return 1
...
... def func2():
... return 2
... """
>>>
>>> tree = ast.parse(code)
>>> [x.name for x in ast.walk(tree) if isinstance(x, ast.FunctionDef)]
['func1', 'func2']
What about this, please let me know if that works:
import ast
import compiler.ast
code = """\
def func1():
return 1
def func2():
return 2
"""
n = compiler.parse(code).getChildNodes()
print n[0].nodes[0].name

in python ,if i edit this: type("myclass", (foo,), {"bar()", barbar}, how can i access the attribute "bar()"

>>> FooChild = type("FooChild", (Foo,), {"echobar()":echo_bar})
>>> FooChild().echobar()
Traceback (most recent call last):
File "<pyshell#214>", line 1, in <module>
FooChild().echobar()
AttributeError: 'FooChild' object has no attribute 'echobar'
>>> FooChild().echobar
Traceback (most recent call last):
File "<pyshell#215>", line 1, in <module>
FooChild().echobar
AttributeError: 'FooChild' object has no attribute 'echobar'
>>> hasattr(FooChild, "echobar()")
True
>>> FooChild().echobar()()
Traceback (most recent call last):
File "<pyshell#217>", line 1, in <module>
FooChild().echobar()()
AttributeError: 'FooChild' object has no attribute 'echobar'
Remove those parentheses:
FooChild = type("FooChild", (Foo,), {"echobar":echo_bar})
The name of a function is without the parentheses. Appending them means to call the function. Without the parentheses you have a reference on the function itself (e. g. for passing a function to things like sort or map).
echobar() is an invalid identifier in python, so you can't access it directly i.e using the dot syntax:
>>> FooChild = type("FooChild", (Foo,), {"echobar()":10})
Use __dict__ or getattr:
>>> FooChild.__dict__['echobar()']
10
>>> getattr(FooChild, 'echobar()')
10
If you want to use it as an attribute then simply get rid of the parenthesis:
>>> FooChild = type("FooChild", (Foo,), {"echobar":10})
>>> FooChild.echobar
10
If you want to use it as a method, then:
>>> def echobar(self):return 10
>>> FooChild = type("FooChild", (Foo,), {'echobar':echobar})
>>> FooChild().echobar()
10
If you pretend to have fancy function with name echobar() in you class, only mean of accessing it is getattr:
class Foo(object):pass
echo_bar =lambda *a: 'bar'
FooChild = type("FooChild", (Foo,), {"echobar()":echo_bar})
print getattr(FooChild(), 'echobar()')()
# bar

Categories

Resources