This is for a project I am working on to help my own workflow, and nothing that is for production. So I understand that what I am doing is probably definitely not the right thing to do, but I am curious if it is possible anyways.
I have some code like this:
A.py:
from B import *
def f1():
...
def f2():
...
...
Is there any way for module B, when imported, to get a list of the functions defined in the importer, A.py?
I thought about using the inspect module, to inspect the call stack. But I was unsure where the entry point would be, I assume it would be in the global scope of B.py. I am also unsure what the call stack looks like when importing a module.
Any help would be appreciated.
Thanks!
If you know what module you are going to import B.py in then you could have something like this:
A.py
import B
def f1():
return 1
def f2():
return 1
def f3():
return 1
if __name__=="__main__":
print temp.allF()
B.py
import inspect, A
def allF():
return inspect.getmembers(A, inspect.isfunction)
When you run A.py it will give you a list of functions.
I'm not sure if there is a way to access the script which imports a given module, but if this is possible then you could change B.py slightly to use this.
Related
Sometimes, I see examples like this, but I don't understand how do they work. Imported module uses function without any places in which this function is set to use. Please can someone explain me how to use them.
Example:
from some_package import *
def some_func():
# do_something
pass
imported_func()
And then imported_func somehow defines some_func and uses it. How is this implemented?
When I tried to call some_func from module.py I received an error. Again: idea is to use function from imported file which was defined in importing file. I couldn't find answer in google.
I tried:
from f.module import *
obj = cls()
def some_func():
for _ in range(100):
print("smth")
obj.imported_func()
Code in main.py
class cls:
#staticmethod
def imported_func():
some_func()
Code in module.py
I have main.py and folder f in one directory. In folder f I have module.py
The way to do this is at first import __main__ then call __main__.some_func(), but remember, it's not a good practice because at least you are reserving name, what can become common reason for errors.
I'm having a problem with importing files which can be simplified as this:
a.py:
import b
a = 0
b.foo()
b.py:
import a
def foo():
a.a=4
So, what I'm trying to do is: in file a.py call the function foo() from b.py which would then change the value of a variable that is in a.py. This is the error I get:
AttributeError: module 'b' has no attribute 'foo'
What am I doing wrong? What would be the proper way to do this?
your import is circular. you need to come up with a way of testing that with a non-circular import. e.g. create a new main file that you execute; import a.a and b.foo there:
main.py
from b import foo
import a
a.a = 7
foo()
a.py
a = 0
b.py
import a
def foo():
a.a=4
First and foremost thing is making circular import, and fixing it is not a good idea.
But try to do small change in your code and solve.
a.py:
from b import foo
a = 0
foo()
print a
b.py:
def foo():
import a as filea
filea.a=4
when you run a.py, watch the print a, it is executing two times. You need to be at your own risk by fixing lot of such things.
Instead of doing all circus, better to avoid circular import.
I'm confused about what happens if you tread a module as a singleton.
Say I have a module conf.py, that contains some configuration parameters which need to be accessed by multiple other files. In conf.py, I might have this piece of code (and nothing else):
myOption = 'foo' + 'bar'
If I now import it first in a.py, and then in b.py, my understanding is that the first time it is imported (in a.py), the string concatenation will be executed. But the second time it is imported (in b.py), conf.myOption already has its value, so no string concatenation will be executed. Is this correct?
If after doing these two imports, I then execute the following in b.py
conf.myOption = 'aDifferentFoobar'
then obviously b.py would now see this new value. Would a.py see the same value, or would it still see 'foobar'?
I believe (but correct me if I'm wrong) that imports are always referred to by reference, not by value? And I'm guessing that's what the above questions boil down to.
Try it and see:
mod.py:
def foo():
print("in foo()")
return "foo"
bar = foo()
opt = "initial"
b.py:
import mod
mod.opt = "changed"
a.py:
import mod
import b
print(mod.bar)
print(mod.opt)
Execute a.py:
$ python3.4 a.py
Output:
in foo()
foo
changed
We learn:
foo() is only executed once
mod.opt is changed by b.py
a.py sees the changed value of mod.opt
bonus: the order of imports in a.py does not matter
this is probably a dumb question, but wasnt too sure what else to do.
main.py
import module2
global x
hello="Hello"
x=module2.message()
x.say()
module2.py
class message:
def say():
print hello
When I print hello, i am referring to the hello variable in main.py however this method will return an error. Does anyone know the solution? (i would prefer not to pipe the hello variable into the function)
The only reliable solution is called encapsulation.
So, basically, you could change your code to look like that:
main.py
import module2
global x
hello="Hello"
x=module2.message(hello)
x.say()
module2.py
class message:
def __init__(self, hello):
self.hello = hello
def say():
print self.hello
Plus try to follow coding style of Python - life of you and future developers of your code will be easier.
Multiple options, but do note that one module cannot ever access the calling module directly.
Simply pass hello as a variable (def say(msg): print msg)
Pass all variables in main.py to module2: def say(g): print g['hello'] and say(globals())
Store it somewhere, then extract it when you need it.
Since main.py imports module2.py, you can access the globals defined in moule2 in main.
In your case since module2 is not importing main, so the globals in main is not accessed in module2.
one solution is that defined by #Tadeck
In this particular example, it's totally OK for module2.py to import main.py, there are some gotcha's though.
The most obvious is that main.py is probably being run from the command line, like python main.py, which has the effect of making that file think it's called __main__. You could import that module in module2, but that's sort of unusual; it's called "main.py" and you want to import main. Doing so will cause the module to be imported a second time.
For that to be OK, you have to arrange for importing the file to have no side effects unless it's imported as __main__. A very common idiom in python is to test that condition at the end of a module.
import module2
global x
hello="Hello"
def main():
x=module2.message()
x.say()
if __name__ == '__main__':
main()
And now it's just fine for module2.py to actually import main. On the other hand, importing variables from one module into another gets hard to predict when the imports can be recursive, you may not have that variable yet because the module is already trying to import you. On the other hand, it's always safe to refer to a variable in a module using dotted syntax. So your module2.py should be:
import main
class message:
def say():
print main.hello
which also makes it more obvious just where hello came from.
I've following use case:
a.py:
import b
import c
c.fun()
b.py:
def fun():
print 'b'
c.py:
def fun():
b.fun()
python a.py doesn't work. It fails with NameError: global name 'b' is not defined.
My understanding of import in python was that a name is added in sys.modules. If that is the case then c.py should also see module b. But apparently that is not the case. So can anyone explain what exactly happens when a module is imported.
Thanks.
The module c.py has to import b in order to get this working...
When importing a module then it is added to the globals-dictionary that is available in the current script's scope only (use "globals()" to print its content)
You have to add all modules which you want to use in that script.
Other way to pass that module in function argument and after that you can call that modules method.
The other way is to add it in _ _ builtins _ _ which is better explain in other post
You have added b and c to the a module, but but not to the c module. When you are inside a module, you can only see what has been added to it. b and c are added to sys.modules, but you haven't imported sys, and you aren't using sys.modules['b'].