How to import/call between files in your own module? - python

I am trying to understand how to write your own modules, by trying to create a simple one, but I don't seem to understand how to use the __init__ file, and this whole import stuff works.
So right now I have a package called "helloWorld", and the structure looks like this:
helloWorld
__init__.py
helloWorldFile.py
helloBonjourFile.py
and these are the contents for each file:
__init__.py:
from helloWorldFile import helloWorldClass
helloWorldFile.py:
import helloBonjourFile
class helloWorldClass():
def __init__(self):
self.keyword = 'Hello Beautiful World'
def hello(self):
print self.keyword
helloBonjourFile.run()
helloBounjourFile.py:
def run():
print 'Bonjour Mon Ami!'
So the idea is, i want to run whatever that is in "helloBonjourFile" from "helloWorldFile", so I try running this in a Python shell:
import helloWorld
reload(helloWorld)
helloWorld.helloWorldClass().hello()
It prints out the "Hello Beautiful World" part fine, but after that i keep getting an error:
AttributeError: 'module' object has no attribute 'run'
I am pretty sure I am going about this incorrectly, how do i correctly run both the contents of "helloWorld" and "helloBonjour"? I'd like to keep the file that actually runs these things to a minimum...
I also would like to figure out a way to pass arguments into "helloBonjour" if possible...

I figured this out, for anyone else that may be having similar issues, this was caused by editing one file and trying to run from the custom module in the same environment, and was solved by running a reload() command for every file. but you have to do it in the order of files being imported, in my case i had to reload in the following order:
reload(helloBounjourFile)
reload(helloWorldFile)
reload(helloWorld)
and that should do the trick.... if it doesnt try it a few times more for it to refresh (at least that worked for me)...

Related

python get the script which imported my script

I want to make my own programming language based on python which will provide additional features that python wasn't provide, for example to make multiline anonymous function with custom syntax. I want my programming language is so simple to be used, just import my script, then I read the script file which is imported my script, then process it's code and stop anymore execution of the script which called my script to prevent error on syntax...
Let say there are 2 py file, main.py and MyLanguage.py
The main.py imported MyLanguage.py
Then how to get the main.py file from MyLanguage.py if main.py can be another name(Dynamic Name)?
Additional information:
I using python 3.4.4 on Windows 7
Like Colonder, I believe the project you have in mind is far more difficult than you imagine.
But, to get you started, here is how to get the main.py file from inside MyLanguage.py. If your importing module looks like this
# main.py
import MyLanguage
if __name__ == "__main__":
print("Hello world from main.py")
and the module it is importing looks like this, in Python 3:
#MyLanguage.py
import inspect
def caller_discoverer():
print('Importing file is', inspect.stack()[-1].filename)
caller_discoverer()
or (edit) like this, in Python 2:
#MyLanguage.py
import inspect
def caller_discoverer():
print 'Importing file is', inspect.stack()[-1][1]
caller_discoverer()
then the output you will get when you run main.py is
Importing file is E:/..blahblahblah../StackOverflow-3.6/48034902/main.py
Hello world from main.py
I believe this answers the question you asked, though I don't think it goes very far towards achieving what you want. The reason for my scepticism is simple: the import statement expects a file containing valid Python, and if you want to import a file with your own non-Python syntax, then you are going to have to do some very clever stuff with import hooks. Without that, your program will simply fail at the import statement with a syntax error.
Best of luck.

Cant run code from imported file

How can I run a function I have created in another file? I know there are many questions asking this but my code is so simple I dont get how it doesn't work.
In one file called Testfile I have
def greeting():
print("Hello")
and in the other I have
import Testfile
greeting()
but when I run the code I get the error
"name 'greeting' is not defined"
import Testfile
Testfile.greeting()
or
from Testfile import greeting
greeting()
you have to specify which module the function is coming from with a . or you tell it when you are importing.
You must call the function after the module that contains it:
import Testfile
Testfile.greeting()
Note that this approach is better because this may lead to namespace conflicts and prevents the scalability of your program.
Please follow PEP 8, section module names

Trouble remembering import rules in Python

It's been a while since I have used Python and am stumbling already at a simple import!
statements.py:
str = "hello"
main.py:
import statements
print statements.str
Obviously the final program will have more going on, and the statements will be stuff like URLs. For this simple example however with both files sitting side by side in the same folder I get the following error on running main.py:
AttributeError: 'module' object has no attribute 'str'
I know I am doing something terribly silly, but I can't see what it is. Searching around it looks fine. Any help/insight is appreciated.
You used the import statement correctly. The error then can be caused by either importing a different module with the same name, or by having altered the module after already having imported it.
You can check print statements.__file__ to see what module Python found instead when importing, and you can use the reload() function to ask Python to reload the module from disk if you altered it.

Access part of module from pytest

I have an issue accessing part of imported module from the pytest.
Here is branch with code referenced below: https://github.com/asvc/snapshotr/tree/develop
In particular, when running this test, it works as expected for test_correct_installation() but test_script_name_checking() fails with AttributeError.
import main as ss
import os
class TestInit:
def test_correct_installation(self):
assert os.path.exists(ss.snapr_path)
assert os.path.isfile(ss.snapr_path + "/main/markup.py")
assert os.path.isfile(ss.snapr_path + "/main/scandir.py")
def test_script_name_checking(self):
assert ss.ssPanel.check_script('blah') is None # Here it fails
Link to the main which is being tested
What I'm trying to do is to "extract" isolated piece of code, run it with known data and compare result to some reference. Seems like extraction part doesn't work quite well, best practises for such cases would be greatly appreciated.
Traceback:
AttributeError: 'module' object has no attribute 'ssPanel'
I have tried a small hack in the test_init.py:
class dummy():
pass
nuke = dummy()
nuke.GUI = True
But it (obviously) doesn't work as nuke.GUI is being redefined in __init__.py upon every launch.
This is a quite complex situation. When you import main in test_init.py, it will import main/__init__.py and execute all the code. This will cause nuke being imported and also, if nuke.GUI is False, there will not be ssPanel, as you can see.
The problem is that, you can't fake a dummy nuke in the test script. It won't work. Because before the test is running, the real nuke was already imported.
My suggestion would be seperate ssPanel into another python file. Then in __init__.py we can do:
if nuke.GUI:
from sspanel import ssPanel
And in test scripts, we can also easily import it using:
from main.sspanel import ssPanel

import ... as ... appears to fail, 'module' has no attribute

have a python web service based on webware for python. In this app, there a multiple "contexts", essentially extensions of the base app with specializations. There are five of these. The one added today is throwing an error, but the others added days ago do not.
import MyModule as mv
class Main():
def __init__(self):
self.vendorcode = mv.id
The code above raises the error at "self.vendorcode = mv.id" saying the module does not have the attribute "id". The file "MyModule.py" that is imported contains the following:
# config parameters
id = 'TEST'
code = 'test_c'
name = 'test_n'
There is nothing else in the file.
Why would this setup work in four other sub directories, aka "contexts", but not in this last one? To put this another way, what should I be looking for? I have confirmed file permissions and file char set type, which appear to fine.
UPDATE: I changed "id" to "ident" but the error was still raised. Using the print verifies that the module file is the correct one. Using the python 2.4.3 interpreter, I see that the file is loaded. In the sample below "TRANS" is the expected return value.
>>> import MoluVendor as mv
>>> print mv.ident
TRANS
>>>
So I wrote a quick test, saved it as a file in the directly with MyModule, as follows:
import MyModule as mv
class MainTest:
def __init__(self):
self.vendorcode = mv.ident
def showme(self):
print self.vendorcode
if __name__ == '__main__':
mt = MainTest()
mt.showme()
That reports correctly too. So the import is working in the simple case.
What bothers me is that there are four other sets of files, including a "MyModule.py" in each, that work fine. I compared the code the code and I cannot find any differences. All of these files sets are invoked by one app running as a deamon in Apache. For that reason, having only one not work is perplexing.
I went through the files involved and checked each for gremlins. That is, I made certain the files were ASCII, no unicode or embedded characters, and saved them using an acceptable code page spec. I reloaded the app and everything now works.
So, in the end, the problem was between the chair and the keyboard. When I modified the app files for the new "context", I neglected (apparently) to save the files in the proper format.

Categories

Resources