When a.py has this code:
class A():
def __init__(self):
print 'hi'
I use class A with this code:
import a
b = a.A()
I need to do the same thing with __import__, and I tried this page:Why does Python's __import__ require fromlist?
__import__("a", fromlist=[])
#import a
b = a.A()
However, I got name 'a' is not defined error. What might be wrong?
__import__ returns a module. You need to bind the result to a name:
a = __import__("a")
a.A()
Related
testa.py
class A:
s1 = 333
__age = 0
def __init__(self,age ):
self.__age=age
return
def __del__(self):
return
#private
def __doSomething(self, s):
print self.__age
return
#public
def doSomething(self, s):
self.__doSomething(s)
print s
test.py
import sys
import testa
a=A(111)
a.doSomething('222')
run
python test.py
it reports error:
NameError: name 'A' is not defined
your comment welcome
Use
a=testa.A(111)
You must name the package unless you import A explicitly e.g
from testa import A
Remember this:
Doing: import mymodule does not import the whole methods and attributes of mymodule to the namespace, so you will need to refer to mymodule, everytime you need a method or attribute from it, using the . notation, example:
x = mymodule.mymethod()
However, if you use:
from mymodule import *
This will bring every method and attribute of mymodule into the namespace and they are available directly, so you don't need to refer to mymodule each time you need to call one of its method or attribute, example:
from mymodule import *
x = mymethod() #mymethod being a method from mymodule
You can also import specific method if you don't want to bring the whole module:
from mymodule import myMethod
For further details, read the Python docs:
https://docs.python.org/2/tutorial/modules.html
I want to list variables "defined" in a module. And then I found there is no way to distinct variables defined in the module and variables imported from other modules. Is there any way to know if a variable is imported?
I KNOW inspect.getmembers and inspect.getmodule and dir but my concern is variable, not function or class definition.
AND I KNOW I COULD IMPORT MODULE RATHER THAN IMPORT VARIABLE FROM MODULE.
I just want to know is there a way or not :).
a.py, define a class
class A(object):
pass
b.py, define a instance using class A
from a import A
ins_b = A()
c.py, define another instance using class A and
from a import A
from b import ins_b
ins_c = A()
I want to list variables like this:
["b.ins_b", "c.ins_c"]
but actually I could do is :
{
<a.A instance at pos1>: ["b.ins_b", "c.ins_b"],
<a.A instance at pos2>: ["c.ins_c"],
}
OK. Thanks to #juanpa.arrivillaga I know it is impossible to do this.
And I just change the problem: how to know "the module which object is created" and "the attr name which the object is assigned".
I try to find something like "metaclass", maybe "metamodule" but I find it changes many behaviors which I do not need.
So according to "How to use inspect to get the caller's info from callee in Python?" and "Retrieve module object from stack frame", I do some trick to realize my idea.
import inspect
import re
attr_r = re.compile(u"\s*([^\s=]+)\s*=")
class A(object):
def __init__(self):
pre_frame = inspect.currentframe().f_back
frame_info = inspect.getframeinfo(pre_frame)
self.init_module_name = inspect.getmodule(pre_frame).__name__
self.init_attr_name = ""
if len(frame_info[3]) > 0:
line = frame_info[3][0]
m = attr_r.match(line)
if m:
self.init_attr_name = m.group(1)
the method to get attr name is trick but work for me.
# init_module_name == "a"
a = A()
print a.init_module_name, a.init_attr_name
# init_module_name == "a"
a = b = A()
print a.init_module_name, a.init_attr_name
# init_module_name == ""
a = \
A()
print a.init_module_name, a.init_attr_name
Is there a way so that the following code:
import traceback
def log(message):
print "%s: %s" %(traceback.extract_stack()[0:-1][-1][2], message)
def f1():
log("hello")
class cls(object):
def f1(self):
log("hi there")
f1()
mycls = cls()
mycls.f1()
displays:
f1: hello
cls.f1: hi there
instead of:
f1: hello
f1: hi there
?
I tried to use module 'inspect' but was not successful...
Julien
EDIT:
The point here is for 'log' function to be able to retrieve its caller
name on its own (using traceback, inspect, or any mean necessary).
I do not want to pass the class name, or anything else than 'message'
to the 'log' function.
So I finally came up this method:
#!/usr/bin/env python3
def log(message):
import inspect
import gc
code = inspect.currentframe().f_back.f_code
func = [obj for obj in gc.get_referrers(code) if inspect.isfunction(obj)][0]
print(func.__qualname__, message)
It needs python3 so that __qualname__ can be used.
The inspect module is very powerful, and can be used in a similar fashion to the way you use traceback to get the name of the function, and probably also the class name. But you can simply make use of the fact that you have the self instance variable, which knows of its own type/class:
import inspect
class cls(object):
def f1(self):
this_class_name = type(self).__name__
this_func_name = inspect.currentframe().f_code.co_name
print(this_class_name, this_func_name)
mycls = cls()
mycls.f1()
Classes B and C both derive from base class A, and neither override A's method test(). B is defined in the same module as A; C is defined in a separate module. How is it that calling B.test() prints "hello", but calling C.test() fails? Shouldn't either invocation end up executing A.test() and therefore be able to resolve the symbol "message" in mod1's namespace?
I'd also gratefully receive hints on where this behaviour is documented as I've been unable to turn up anything. How are names resolved when C.test() is called, and can "message" be injected into one of the namespaces somehow?
FWIW, the reason I haven't used an instance variable (e.g. set A.message = "hello") is because I'm wanting to access a "global" singleton object and don't want to have an explicit referent to it in every other object.
mod1.py:
import mod2
class A(object):
def test(self):
print message
class B(A):
pass
if __name__ == "__main__":
message = "hello"
A().test()
B().test()
mod2.C().test()
mod2.py:
import mod1
class C(mod1.A):
pass
output is:
$ python mod1.py
hello
hello
Traceback (most recent call last):
File "mod1.py", line 14, in <module>
mod2.C().test()
File "mod1.py", line 5, in test
print message
NameError: global name 'message' is not defined
Many thanks!
EOL is correct, moving the "main" part of the program into a new file mod3.py does indeed make things work.
http://bytebaker.com/2008/07/30/python-namespaces/ further clarifies the issue.
In my original question, it turns out that the variable message ist stored in the __main__ module namespace because mod1.py is being run as a script. mod2 imports mod1, but it gets a separate mod1 namespace, where the variable message does not exist. The following code snippet demonstrates more clearly as it writes message into mod1's namespace (not that I'd recommend this be done in real life), causing the expected behaviour.
import sys
class A(object):
def test(self):
print message
class B(A):
pass
if __name__ == "__main__":
import mod2
message = "hello"
sys.modules["mod1"].message = message
A().test()
B().test()
mod2.C().test()
I think the best real-world fix is to move the "main" part of the program into a separate module, as EOL implies, or do:
class A(object):
def test(self):
print message
class B(A):
pass
def main():
global message
message = "hello"
A().test()
B().test()
# resolve circular import by importing in local scope
import mod2
mod2.C().test()
if __name__ == "__main__":
# break into mod1 namespace from __main__ namespace
import mod1
mod1.main()
Could you use a class attribute instead of a global? The following works
import mod2
class A(object):
message = "Hello" # Class attribute (not duplicated in instances)
def test(self):
print self.message # Class A attribute can be overridden by subclasses
class B(A):
pass
if __name__ == "__main__":
A().test()
B().test()
mod2.C().test()
Not using globals is cleaner: in the code above, message is explicitly attached to the class it is used in.
That said, I am also very curious as to why the global message is not found by mod2.C().test().
Things work as expected, though, if the cross-importing is removed (no main program in mod1.py, and no import mod2): importing mod1 and mod2 from mod3.py, doing mod1.message = "Hello" there and mod2.C().test() works. I am therefore wondering if the problem is not related to cross-importing…
Name of the file from where code is running
Name of the class from where code is running
Name of the method (attribute of the class) where code is running
Here is an example of each:
from inspect import stack
class Foo:
def __init__(self):
print __file__
print self.__class__.__name__
print stack()[0][3]
f = Foo()
import sys
class A:
def __init__(self):
print __file__
print self.__class__.__name__
print sys._getframe().f_code.co_name
a = A()
self.__class__.__name__ # name of class i'm in
for the rest the sys and trace modules
http://docs.python.org/library/sys.html
http://docs.python.org/library/trace.html
Some more info:
https://mail.python.org/pipermail/python-list/2001-August/096499.html
and
http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html
did you want it for error reporting because the traceback module can handle that:
http://docs.python.org/library/traceback.html
Be very careful. Consider:
class A:
pass
B = A
b = B()
What is the 'class name' of b here? Is it A, or B? Why?
The point is, you shouldn't need to know or care. An object is what it is: its name is very rarely useful.