How to import another external python module? - python

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.

Related

Python how to use function in imported file defined in importing file?

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.

How to use a module/class function/method in a different module/class without importing the module/class or knowing the file architecture in Python?

I'm a somewhat of an intermediate Python programmer but there's something that's been bugging me for a while. I'm trying to unify code to make it reusable by many projects. The problem I am facing is how to access function (or methods for that matter) by a certain class (or procedural code) without importing the module/class. I want my code to not know about the existence of other files/modules.
Here's an example.
Imagine I have a the following file architecture for my project (that would be reused by other project but with a slight variation):
Main Folder
main.py
Folder1>module1>func1
Folder2>module2>func2 (func2 calls func1, let's say func1 is a common math operation, like finding whether a point is on a plane within a tolerance)
Now, in main.py, I import both module1 and module2
let's say I have a function in main.py that calls func2 as such
## In main.py
def call_func1():
module2.func2()
## In module1.py
def is_point_on_plane():
print("testing")
## In module2.py
def func2():
is_point_on_plane() ## This is a function that is currently in module1
Now, I don't want module1 or module2 to know anything about each other, or even that the other exists. I'm trying to avoid any imports.
The way I'm working around this is to pass is_point_on_plane as a parameter to func2 in main.py
def call_func1():
fcToCall = module1.is_point_on_plane
module2.func2(fcToCall)
## In module1
def is_point_on_plane():
print("testing")
## In module2
def func2(fcToCall):
fcToCall()
I am sure there is a better way to do this. A more Pythonic way. In whichever case, I need module1 and module2 to be completely independent and avoid any imports.
you could import the file name of the project you want for example:
"if my want to use another def function of a file called 'main.py' then i will write
import main
main.call_func1()

Import function from another python file, but use definitions from original file

Say I have file1.py and file2.py, and inside file2.py I have func2() but it uses variables and definitions made exclusively in file1.py...how can I import and call func2() in file1.py, without throwing "NameError: name 'dependency1' is not defined"?
file2.py:
def func2():
print('do something cool')
file1.py:
# here I import and define a bunch of things, e.g
from module1 import dependency1
from file2 import func2
func2()
I think the simple answer is that you can't. What you are trying to do is use a circular reference, which is why your implementation is breaking. File2.py is referencing variables from file1.py, which is referencing a function from file2.py.
Not to mention the bad coding convention, but it would also be a nightmare to develop further from here if anything were to break.
Long story short: do yourself a favor and work on some encapsulation. Make each file able to function on their own, and then you can do some importing for your final product.
edit: That in a test bench I was able to get file2.py to run, but not file1.py. This is still not your intention, but I wanted to point it out so you are not confused. Regardless, it would still be better to just do yourself the favor and separate out your files.

how to create top-level module function from another function?

Given a module mymodule with an __init__.py file how can I define a functions of mymodule from another function within that file?
__init__.py code outline:
def a():
THISMODULE.__dict__["b"] = lambda: print("this is not weird")
a()
b() # Expect "this is not weird" output
mymodule comes as a replacement for anothermodule and I want to make the code change as simple as replacing import anothermodule as thething with import mymodule as thething. Since I don't implement all the functions of anothermodule just yet, I would like to send the user a notification about it instead of crashing with "not defined".
__name__ is a module attribute set by the import machinery, which evaluates to the name of the current module. Adding this to the top of your file:
import sys
THISMODULE = sys.modules[__name__]
And the rest of what you already have should work correctly.

new import with imports pre-def

how to import foo module like this example.
main.py :
import time
from foo import main
return main()
foo.py :
def main()
print 'hello', time.time()
I tried to explain, there are two or more files, I wanted to upload a import already defined by another file without defining in what will be loaded, like my example
Unfortunately that's not how Python works. Names must be available in the scope in which they are used. There is a scope that is always accessible, but modifying it is generally frowned upon since it makes code harder to read and use.

Categories

Resources