Python: isinstance() undefined global name - python

I'm new with Python and I'm trying to use classes to program using objects as I do with C++.
I wrote 3 .py files.
a.py
from b import *
class A:
def __init__(self):
self.m_tName = "A"
def test(self):
tB = B()
tB.do( self )
b.py
from a import *
class B:
def __init__(self):
self.m_tName = "B"
def do(self, tA ):
if not isinstance( tA, A ):
print ( "invalid parameter" )
print( "OK" )
demo.py:
from a import *
if __name__ == "__main__":
tA = A()
tA.test()
As you can see I want to use a A() object to call the member function test() that creates a B() object and call the member function do() that uses a A() object.
So in B::do() I want to check the parameters using the built-in function isinstance(). But python tells me that there's a NameError: global name 'A' is not defined.
The A() class file is imported at the top of the b.py file.
Does anyone know what I'm doing wrong here ?

As pointed in some comment, circular dependencies are not well handled if imported in the form from a import A.
In short, the problem with ... import * is that is causes the local scope to have all its declarations overridden, in effect making the identification of from which module (in your case) a class comes from. This causes exactly what you are facing.
Changing the import statement in the following way, together with a classified reference to a.A, produces OK as output.
import a
class B:
def __init__(self):
self.m_tName = "B"
def do(self, tA ):
print tA
if not isinstance( tA, a.A ):
print ( "invalid parameter" )
print( "OK" )
As a bit of additional information, this has already been discussed in Why is "import *" bad?. I would point in special to this answer: https://stackoverflow.com/a/2454460/1540197.
**Edit:**This article explain the import confusion.

You have a circular dependancy, a.py and b.py import each other.
You could move either import statement inside the method where it is used.
So b.py would become:
class A:
def __init__(self):
self.m_tName = "A"
def test(self):
from b import B
tB = B()
tB.do( self )

Related

How to change variable in a module?

For a.py:
class a():
def __init__(self,var = 0):
self.var = var
def p(self):
print(self.var)
For b.py:
import a
a.var=2
o=a()
o.p()
What I want is: 2.
But it shows: 0.
When I import the module, ta, I want to use add_all_ta_features in this module, which use other class in this module. Meanwhile, I want to change the variable in other class, but the result is still the same.
Could anyone help me with that? Thank you.
For a.py:
class a():
def __init__(self,var = 0):
self.var = var
def p(self):
print(self.var)
For b.py
import a
ob=a.a(2)
## Or you can do
## ob=a.a()
## ob.var=2
p=ob.p()
In this case, your output will be 2, What exactly is happening that your class name and the python module name are the same. In here you have just imported the module, but when you create an object of any class you have to use the class name using the above method or by these methods.
## Method 2
from a import a
ob=a(2)
## Or you can do
## ob=a()
## ob.var=2
p=ob.p()
or
## Method 3
import a as obj
ob=obj.a(2)
## Or you can do
## ob=obj.a()
## ob.var=2
p=ob.p()
Go ahead and initialise a
b.py:
import a
an_a = a()
a.var = 23 #set whatever you want
print(a.var)

Magic mock assert_called_once vs assert_called_once_with weird behaviour

I am noticing a weird behavior with assert_called_once and assert_called_once_with in python. This is my real simple test:
File module/a.py
from .b import B
class A(object):
def __init__(self):
self.b = B("hi")
def call_b_hello(self):
print(self.b.hello())
File module/b.py
class B(object):
def __init__(self, string):
print("created B")
self.string = string;
def hello(self):
return self.string
These are my tests:
import unittest
from mock import patch
from module.a import A
class MCVETests(unittest.TestCase):
#patch('module.a.B')
def testAcallBwithMockPassCorrect(self, b1):
a = A()
b1.assert_called_once_with("hi")
a.call_b_hello()
a.b.hello.assert_called_once()
#patch('module.a.B')
def testAcallBwithMockPassCorrectWith(self, b1):
a = A()
b1.assert_called_once_with("hi")
a.call_b_hello()
a.b.hello.assert_called_once_with()
#patch('module.a.B')
def testAcallBwithMockFailCorrectWith(self, b1):
a = A()
b1.assert_called_once_with("hi")
a.b.hello.assert_called_once_with()
#patch('module.a.B')
def testAcallBwithMockPassWrong(self, b1):
a = A()
b1.assert_called_once_with("hi")
a.b.hello.assert_called_once()
if __name__ == '__main__':
unittest.main()
My problem as stated in the name of the function is:
Test 1 passes correctly
Test 2 passes correctly
Test 3 fails correctly (I've removed the call to b)
Test 4 passes I am not sure why.
Am I doing something wrong? I am not sure but reading the documentation docs python:
assert_called_once(*args, **kwargs)
Assert that the mock was called exactly once.
This is old, but for others landing here...
For python < 3.6, assert_called_once isn't a thing and so you're actually making a mocked function call which doesn't error
Please see: http://engineroom.trackmaven.com/blog/mocking-mistakes/
You can check the call count instead.

Is there a magic function which is used to parse raw string into object? [duplicate]

Given a string as user input to a Python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:
class Foo:
pass
str_to_class("Foo")
==> <class __main__.Foo at 0x69ba0>
Is this, at all, possible?
This could work:
import sys
def str_to_class(classname):
return getattr(sys.modules[__name__], classname)
Warning: eval() can be used to execute arbitrary Python code. You should never use eval() with untrusted strings. (See Security of Python's eval() on untrusted strings?)
This seems simplest.
>>> class Foo(object):
... pass
...
>>> eval("Foo")
<class '__main__.Foo'>
You could do something like:
globals()[class_name]
You want the class Baz, which lives in module foo.bar. With Python 2.7,
you want to use importlib.import_module(), as this will make transitioning to Python 3 easier:
import importlib
def class_for_name(module_name, class_name):
# load the module, will raise ImportError if module cannot be loaded
m = importlib.import_module(module_name)
# get the class, will raise AttributeError if class cannot be found
c = getattr(m, class_name)
return c
With Python < 2.7:
def class_for_name(module_name, class_name):
# load the module, will raise ImportError if module cannot be loaded
m = __import__(module_name, globals(), locals(), class_name)
# get the class, will raise AttributeError if class cannot be found
c = getattr(m, class_name)
return c
Use:
loaded_class = class_for_name('foo.bar', 'Baz')
I've looked at how django handles this
django.utils.module_loading has this
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
msg = "%s doesn't look like a module path" % dotted_path
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
module = import_module(module_path)
try:
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
module_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
You can use it like import_string("module_path.to.all.the.way.to.your_class")
import sys
import types
def str_to_class(field):
try:
identifier = getattr(sys.modules[__name__], field)
except AttributeError:
raise NameError("%s doesn't exist." % field)
if isinstance(identifier, (types.ClassType, types.TypeType)):
return identifier
raise TypeError("%s is not a class." % field)
This accurately handles both old-style and new-style classes.
If you really want to retrieve classes you make with a string, you should store (or properly worded, reference) them in a dictionary. After all, that'll also allow to name your classes in a higher level and avoid exposing unwanted classes.
Example, from a game where actor classes are defined in Python and you want to avoid other general classes to be reached by user input.
Another approach (like in the example below) would to make an entire new class, that holds the dict above. This would:
Allow multiple class holders to be made for easier organization (like, one for actor classes and another for types of sound);
Make modifications to both the holder and the classes being held easier;
And you can use class methods to add classes to the dict. (Although the abstraction below isn't really necessary, it is merely for... "illustration").
Example:
class ClassHolder:
def __init__(self):
self.classes = {}
def add_class(self, c):
self.classes[c.__name__] = c
def __getitem__(self, n):
return self.classes[n]
class Foo:
def __init__(self):
self.a = 0
def bar(self):
return self.a + 1
class Spam(Foo):
def __init__(self):
self.a = 2
def bar(self):
return self.a + 4
class SomethingDifferent:
def __init__(self):
self.a = "Hello"
def add_world(self):
self.a += " World"
def add_word(self, w):
self.a += " " + w
def finish(self):
self.a += "!"
return self.a
aclasses = ClassHolder()
dclasses = ClassHolder()
aclasses.add_class(Foo)
aclasses.add_class(Spam)
dclasses.add_class(SomethingDifferent)
print aclasses
print dclasses
print "======="
print "o"
print aclasses["Foo"]
print aclasses["Spam"]
print "o"
print dclasses["SomethingDifferent"]
print "======="
g = dclasses["SomethingDifferent"]()
g.add_world()
print g.finish()
print "======="
s = []
s.append(aclasses["Foo"]())
s.append(aclasses["Spam"]())
for a in s:
print a.a
print a.bar()
print "--"
print "Done experiment!"
This returns me:
<__main__.ClassHolder object at 0x02D9EEF0>
<__main__.ClassHolder object at 0x02D9EF30>
=======
o
<class '__main__.Foo'>
<class '__main__.Spam'>
o
<class '__main__.SomethingDifferent'>
=======
Hello World!
=======
0
1
--
2
6
--
Done experiment!
Another fun experiment to do with those is to add a method that pickles the ClassHolder so you never lose all the classes you did :^)
UPDATE: It is also possible to use a decorator as a shorthand.
class ClassHolder:
def __init__(self):
self.classes = {}
def add_class(self, c):
self.classes[c.__name__] = c
# -- the decorator
def held(self, c):
self.add_class(c)
# Decorators have to return the function/class passed (or a modified variant thereof), however I'd rather do this separately than retroactively change add_class, so.
# "held" is more succint, anyway.
return c
def __getitem__(self, n):
return self.classes[n]
food_types = ClassHolder()
#food_types.held
class bacon:
taste = "salty"
#food_types.held
class chocolate:
taste = "sweet"
#food_types.held
class tee:
taste = "bitter" # coffee, ftw ;)
#food_types.held
class lemon:
taste = "sour"
print(food_types['bacon'].taste) # No manual add_class needed! :D
Yes, you can do this. Assuming your classes exist in the global namespace, something like this will do it:
import types
class Foo:
pass
def str_to_class(s):
if s in globals() and isinstance(globals()[s], types.ClassType):
return globals()[s]
return None
str_to_class('Foo')
==> <class __main__.Foo at 0x340808cc>
In terms of arbitrary code execution, or undesired user passed names, you could have a list of acceptable function/class names, and if the input matches one in the list, it is eval'd.
PS: I know....kinda late....but it's for anyone else who stumbles across this in the future.
Using importlib worked the best for me.
import importlib
importlib.import_module('accounting.views')
This uses string dot notation for the python module that you want to import.

Share variables between modules

I have this situation:
library_file1.py:
class A:
def foo(self):
print("bar")
def baz(self):
pass
project_file.py:
from library_file1 import A
class B(A):
def baz(self):
print(the_variable)
library_file2.py:
from project_file import B
the_variable = 7
b = B()
b.foo() # prints "bar"
b.baz() # I want this to print "7", but I don't know how
How do I allow code to be written in project_file.py that can access variables from library_file2.py? The only solution I can think of is this:
project_file.py:
from library_file1 import A
class B(A):
def baz(self, the_variable):
print(the_variable)
library_file2.py:
from project_file import B
the_variable = 7
b = B()
b.foo()
b.baz(the_variable)
but this feels awkward and doesn't scale to many variables like the_variable.
Quite easy: you need the variable to be in project_file.py instead of library_file2.py.
Change project_file to:
from library_file1 import A
the_variable = None
class B(A):
def baz(self):
print(the_variable)
And then in library_file2:
import project_file
from project_file import B
project_file.the_variable = 7
b = B()
b.foo() # prints "bar"
b.baz() # prints "7"
Using an argument is also a good solution (you should avoid globals as much as you can).
There is no such a thing as a truly global variable in python. Variables are always attached to a scope. We usually say that a variable is "global" when it's in the module scope.
The widest scope is the built-in scope, so it would be theoretically possible for you to add something as a built-in. However this is a really bad practice.
Also it doesn't complete fix the problem, because all files could access that new built-in, but they couldn't re-assign it without explicitly mentioning the scope.

How to get the caller's method name in the called method?

Python: How to get the caller's method name in the called method?
Assume I have 2 methods:
def method1(self):
...
a = A.method2()
def method2(self):
...
If I don't want to do any change for method1, how to get the name of the caller (in this example, the name is method1) in method2?
inspect.getframeinfo and other related functions in inspect can help:
>>> import inspect
>>> def f1(): f2()
...
>>> def f2():
... curframe = inspect.currentframe()
... calframe = inspect.getouterframes(curframe, 2)
... print('caller name:', calframe[1][3])
...
>>> f1()
caller name: f1
this introspection is intended to help debugging and development; it's not advisable to rely on it for production-functionality purposes.
Shorter version:
import inspect
def f1(): f2()
def f2():
print 'caller name:', inspect.stack()[1][3]
f1()
(with thanks to #Alex, and Stefaan Lippen)
This seems to work just fine:
import sys
print sys._getframe().f_back.f_code.co_name
I would use inspect.currentframe().f_back.f_code.co_name. Its use hasn't been covered in any of the prior answers which are mainly of one of three types:
Some prior answers use inspect.stack but it's known to be too slow.
Some prior answers use sys._getframe which is an internal private function given its leading underscore, and so its use is implicitly discouraged.
One prior answer uses inspect.getouterframes(inspect.currentframe(), 2)[1][3] but it's entirely unclear what [1][3] is accessing.
import inspect
from types import FrameType
from typing import cast
def demo_the_caller_name() -> str:
"""Return the calling function's name."""
# Ref: https://stackoverflow.com/a/57712700/
return cast(FrameType, cast(FrameType, inspect.currentframe()).f_back).f_code.co_name
if __name__ == '__main__':
def _test_caller_name() -> None:
assert demo_the_caller_name() == '_test_caller_name'
_test_caller_name()
Note that cast(FrameType, frame) is used to satisfy mypy.
Acknowlegement: comment by 1313e for an answer.
I've come up with a slightly longer version that tries to build a full method name including module and class.
https://gist.github.com/2151727 (rev 9cccbf)
# Public Domain, i.e. feel free to copy/paste
# Considered a hack in Python 2
import inspect
def caller_name(skip=2):
"""Get a name of a caller in the format module.class.method
`skip` specifies how many levels of stack to skip while getting caller
name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.
An empty string is returned if skipped levels exceed stack height
"""
stack = inspect.stack()
start = 0 + skip
if len(stack) < start + 1:
return ''
parentframe = stack[start][0]
name = []
module = inspect.getmodule(parentframe)
# `modname` can be None when frame is executed directly in console
# TODO(techtonik): consider using __main__
if module:
name.append(module.__name__)
# detect classname
if 'self' in parentframe.f_locals:
# I don't know any way to detect call from the object method
# XXX: there seems to be no way to detect static method call - it will
# be just a function call
name.append(parentframe.f_locals['self'].__class__.__name__)
codename = parentframe.f_code.co_name
if codename != '<module>': # top level usually
name.append( codename ) # function or a method
## Avoid circular refs and frame leaks
# https://docs.python.org/2.7/library/inspect.html#the-interpreter-stack
del parentframe, stack
return ".".join(name)
Bit of an amalgamation of the stuff above. But here's my crack at it.
def print_caller_name(stack_size=3):
def wrapper(fn):
def inner(*args, **kwargs):
import inspect
stack = inspect.stack()
modules = [(index, inspect.getmodule(stack[index][0]))
for index in reversed(range(1, stack_size))]
module_name_lengths = [len(module.__name__)
for _, module in modules]
s = '{index:>5} : {module:^%i} : {name}' % (max(module_name_lengths) + 4)
callers = ['',
s.format(index='level', module='module', name='name'),
'-' * 50]
for index, module in modules:
callers.append(s.format(index=index,
module=module.__name__,
name=stack[index][3]))
callers.append(s.format(index=0,
module=fn.__module__,
name=fn.__name__))
callers.append('')
print('\n'.join(callers))
fn(*args, **kwargs)
return inner
return wrapper
Use:
#print_caller_name(4)
def foo():
return 'foobar'
def bar():
return foo()
def baz():
return bar()
def fizz():
return baz()
fizz()
output is
level : module : name
--------------------------------------------------
3 : None : fizz
2 : None : baz
1 : None : bar
0 : __main__ : foo
You can use decorators, and do not have to use stacktrace
If you want to decorate a method inside a class
import functools
# outside ur class
def printOuterFunctionName(func):
#functools.wraps(func)
def wrapper(self):
print(f'Function Name is: {func.__name__}')
func(self)
return wrapper
class A:
#printOuterFunctionName
def foo():
pass
you may remove functools, self if it is procedural
An alternative to sys._getframe() is used by Python's Logging library to find caller information. Here's the idea:
raise an Exception
immediately catch it in an Except clause
use sys.exc_info to get Traceback frame (tb_frame).
from tb_frame get last caller's frame using f_back.
from last caller's frame get the code object that was being executed in that frame.
In our sample code it would be method1 (not method2) being executed.
From code object obtained, get the object's name -- this is caller method's name in our sample.
Here's the sample code to solve example in the question:
def method1():
method2()
def method2():
try:
raise Exception
except Exception:
frame = sys.exc_info()[2].tb_frame.f_back
print("method2 invoked by: ", frame.f_code.co_name)
# Invoking method1
method1()
Output:
method2 invoked by: method1
Frame has all sorts of details, including line number, file name, argument counts, argument type and so on. The solution works across classes and modules too.
Code:
#!/usr/bin/env python
import inspect
called=lambda: inspect.stack()[1][3]
def caller1():
print "inside: ",called()
def caller2():
print "inside: ",called()
if __name__=='__main__':
caller1()
caller2()
Output:
shahid#shahid-VirtualBox:~/Documents$ python test_func.py
inside: caller1
inside: caller2
shahid#shahid-VirtualBox:~/Documents$
I found a way if you're going across classes and want the class the method belongs to AND the method. It takes a bit of extraction work but it makes its point. This works in Python 2.7.13.
import inspect, os
class ClassOne:
def method1(self):
classtwoObj.method2()
class ClassTwo:
def method2(self):
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 4)
print '\nI was called from', calframe[1][3], \
'in', calframe[1][4][0][6: -2]
# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()
# start the program
os.system('cls')
classoneObj.method1()
Hey mate I once made 3 methods without plugins for my app and maybe that can help you, It worked for me so maybe gonna work for you too.
def method_1(a=""):
if a == "method_2":
print("method_2")
if a == "method_3":
print("method_3")
def method_2():
method_1("method_2")
def method_3():
method_1("method_3")
method_2()

Categories