Issue with importing my classes - python

Consider that I have 3 files.
I am trying to put different import function in one file and call that file i.e., File2 in this case directly.
File1.py
class generalTools():
def waitAppear():
wait()
File 11.py
class machinedata():
def max():
maxtime()
File2.py
import File1
import File11
self.generalTools = File1.generalTools()
self.machinedata=machinedata.max()
File3.py
from File2 import *
Note here I am not creating an object; just trying to call File1->waitAppear()
self.generalTools.waitAppear(self)
Whenever I execute above code, it throws error saying "generaTool has no instance"
What's wrong with the above code?

Related

Importing function from program in a subdirectory

Using python I launch a script from a certain point. From here, there's the subdirectory "A" where it's contained the file "B.py", which contains a class called "C"
from A import C
Traceback
ImportError: cannot import name 'C' from 'A' (unknown location). Is there an easy way to make python look in A then in B and finally get C? Thank you
If I have a directory structure like the following:
A -----------|
|- B.py
test.py
B.py contains the following code:
class C:
def __init__(self):
print("I made it to C!")
If I'm writing test.py to need an instance of C I need to import like this:
from A.B import C
myInst = C()
And I get the following output when I run test.py
I made it to C!
Alternatively, you can add the path to the directory containing B.py to your PATH with the sys module. To show this, I have put the file E.py in the structure of A/B/C/D/E.py along with an empty file named __init__.py
'=
E.py contains the following code:
class F:
def __init__(self):
print("I made it to C!")
test.py contains the following code:
import sys
sys.path.insert(0, "./A/B/C/D/") # You can put the absolute path
from E import F
myInst = F()
And I get the output:
I made it to C!

Calling __init__.py from another file

I am trying to understand how __init__py works. But I have the following question.
I have the following directory:
myfoldername/
example/
__init__.py
sayhello.py
saybye.py
main.py
Inside the __init__py file I import the sayhello.py and saybye.py files
from example.sayhello import *
from example.saybye import *
Inside the sayhello.py I have two functions:
def hello():
print('hello')
def hello_person(x):
print('hello ' + x)
Why can I not call the both functions in the sayhello.py when I import the module into a separate script main.py?
import example as ex
ex.hello() //prints 'hello'
ex.hello_person('John') //prints module 'example' has no attribute 'hello_person'
Though that shouldn't have happened. but if the issue is still there you can make use of The Zen of Python. Which says
Explicit is better than implicit.
Hence,
from example.sayhello import hello, hello_person

Can't create instance of class from other file in Atom/Hydrogen

I am having problems with Hydrogen in Atom on MacOS when trying to create an instance of a class from another file/module. The code does work when run in the command-line, but not in Atom. I have already set the directory to start kernel in to "Current directory of the file", which enables me to create an object of that other file and use functions, but not classes.
Here is the code in the two respective files. Again, importing File2 is not the problem, neither is using functions from File2 in File1. It is only classes that don't work.
#File1
import File2
from File2 import MyClass
y=MyClass('test')
print(y.name)
#File2
class MyClass:
def __init__(self, x):
self.name=x
Running File1 gives me the error message, when run in Atom.
ImportError Traceback (most recent call last)
<ipython-input-92-444367378d7c> in <module>
----> 1 from File2 import MyClass
ImportError: cannot import name 'MyClass' from 'File2' (/Users/.../File2.py)

Python importing multiple scripts

I've been working on a python script that will require multiple libraries to be imported.
At the moment my directory structure is
program/
main.py
libs/
__init__.py
dbconnect.py
library01.py
library02.py
library03.py
My dbconnect.py which has the following contents
import psycopg2
class dbconnect:
def __init__(self):
self.var_parameters = "host='localhost' dbname='devdb' user='temp' password='temp'"
def pgsql(self):
try:
var_pgsqlConn = psycopg2.connect(self.var_parameters)
except:
print("connection failed")
return var_pgsqlConn
I am able to import and use this in my main.py using
from libs.dbconnect import dbconnect
class_dbconnect = dbconnect()
var_pgsqlConn = class_dbconnect.pgsql()
This works as expected however I am trying to import all of the library scripts each which have similar contents to bellow
def library01():
print("empty for now but this is library 01")
I have added to my __init__.py script
__all__ = ["library01", "library02"]
Then in my main.py I tried to import and use them as bellow
from libs import *
library01()
I am getting the following error
TypeError: 'module' object is not callable
I'll suppose content in your library0x.py are different (the functions/class have different names)
The best way is to import all your subfiles content in the __init__.py
# __init__.py
from .dbconnect import *
from .library01 import *
from .library02 import *
from .library03 import *
Then you can use the following :
from libs import library01, library02
If you want to restrict for some reasons importation with the wildcard (*) in your library0x.py files, you can define a __all__ variable containing all the names of the function you will import with the wildcard :
# library01.py
__all__ = ["library01"]
def a_local_function():
print "Local !"
def library01():
print "My library function"
Then, by doing from .library01 import *, only the function library01 will be import.
EDIT: Maybe i missunderstand the question : here are some ways to import the function library01 in the file library01.py :
# Example 1:
from libs.library01 import library01
library01()
# Example 2:
import libs.library01
libs.library01.library01()
# Example 3:
import libs.library01 as library01
library01.library01()
In your case library01 is a module which contains a function named library01. You import the library01 module and try to call it as a function. That's the problem. You should call the function like this:
library01.library01()

Importing a sub class from a sub folder

New to Python I'm trying to setup a simple OOP-structure of files, folders and classes. Here are the file paths:
C:\Users\Mc_Topaz\Programmering\Python\Terminal\Main.py
C:\Users\Mc_Topaz\Programmering\Python\Terminal\Connections\Connection.py
C:\Users\Mc_Topaz\Programmering\Python\Terminal\Connections\NoConnection.py
Notice Connection.py and NoConnection.py is loacted in sub folder Connections.
Connection.py
class Connection:
def __init__(self):
pass
def ToString(self):
pass
NoConnection.py
from Connection import Connection
class NoConnection(Connection):
def __init__(self):
pass
def ToString(self):
print("No connection")
In the Main.py file I would like to call the ToString() method from each class.
Main.py
from Connections.Connection import Connection
from Connections.NoConnection import NoConnection
connection = Connection()
print(connection.ToString())
noConnection = NoConnection()
print(noConnection.ToString())
When I run the Main.py file I get this error:
C:\Users\Mc_Topaz\Programmering\Python\Terminal>Main.py Traceback
(most recent call last): File
"C:\Users\Mc_Topaz\Programmering\Python\Terminal\Main.py", line 2, in
from Connections.NoConnection import NoConnection
File
"C:\Users\Mc_Topaz\Programmering\Python\Terminal\Connections\NoConnection.py",
line 1, in
from Connection import Connection
ImportError: No module named 'Connection'
It seems that the interpreter cannot import the NoConnection class in my Main.py file due to it cannot import the Connection class from the NoConnection.py file.
I can run Connection.py and NoConnection.py separately with no problems.
I don't understand why the Main.py don't run. I assume is something super simple and I cannot see it due to I'm to green to Python.
For python to recognize a directory is a module, or a collection of python files, that directory must contain a file named __init__.py. That file doesn't need to contain anything code whatsoever, though it can. If you add this file to your Connections directory, the interpreter should be able to import the contained files.
Just to add on to what mobiusklein mentioned: a common practice with __init__.py is to import the objects you use most frequently to avoid redundancy in your imports. In your example your Connections\__init__.py would likely contain:
import Connection
import NoConnection
Then your Main.py could use the following import statements successfully:
from Connections import Connection, NoConnection
I think it's down to relative imports in Python 3.
Change the import line in NoConnection to be explicit...
from Connections.Connection import Connection
and it works in Python3 (it works either way in Python2). Path to Terminal may have to be on you PYTHONPATH environment variable.
"Python 3 has disabled implicit relative imports altogether; imports are now always interpreted as absolute, meaning that in the above example import baz will always import the top-level module. You will have to use the explicit import syntax instead (from . import baz)." from here https://softwareengineering.stackexchange.com/questions/159503/whats-wrong-with-relative-imports-in-python
So when you import Connection from NoConnection it will be looking for it at the Terminal level, not at the Terminal/Connections level.
UPDTAE: Read comments for this post as it contain the solution.
Still don't get this to work. But I have made some changes:
Changed names of classes
> Class Connection = Foo inside Connection.py
> NoConnection = Bar inside NoConnection.py
This is ensure that the interpreter don't get confused if Connection is a module or a class.
Dropped ini.py file
I have dropped the Connections\__init_.py file as this don't seem to be necessary in Python version 3.4.2.
Files still run separately
I can run Connection.py and NoConnection.py separately. So they work.
Main.py
from Connections.NoConnection import Bar
noConnection = Bar()
print(noConnection.ToString())
When running Main.py I get the same error at line 1:
"Cannot find module 'Connection' in NoConnection.py at line 1".
The only logical reason I can see why this error happens is:
The interpreter looks for Connection.py inside my Terminal folder as Python was started from that folder. Even if it's importing the NoConnection.py file from the Connections folder where Connection.py is located.
Is this a bug?

Categories