Imported function not working - python

I am pretty new to Python and am trying to import a function I have made in a separate file. When I run the code I get "TypeError: signal() missing 1 required positional argument: 'handler'". I think it means the signal function is not being passed a single argument but I am pretty sure that is what the for loop does. Where am I going wrong? Also, the files are in the same folder, which is a part of the working directory. The code that calls the function is:
import numpy as np
t=np.linspace(-5,5,200)
import signal
y=[]
for i in t:
y.append(signal.signal(i))
The function code is saved in a file called signal.py. The code is:
def signal(t):
import numpy as np
y=np.cos(t)*np.exp(-abs(t))
return y

It seems you are trying to import a signal from the standard library instead of your own file. Try to import it like this:
from .signal import signal
PS: Since you are new to Python, you should also make sure you have a an __init__.py file in the directory, like so:
/Parent
__init__.py
main.py
signal.py

As suggested by chepner, you have a module name conflict with pythons inbuilt module signal
If the name is not important, then you could change the name.
If the name is important then you could create a package and place the file in that, Then import it.
For example, following will be your directory tree
signal_module/
├── __init__.py
└── signal.py
original_file.py
Then import the signal_module as follows
from signal_module import signal
The __init__.py file is import.
It can be empty, but it needs to be created for python to tree the directory as package.
As you said you are new to python, have a look at this answer to know more about the importance of __init__.py

Related

Importing a function from another directory within a package

I am working with the following directory in Python3.8:
package/
__init__.py
/folder1
__init__.py
file1.py
/folder2
__init__.py
file2.py
/folder3
__init__.py
file3.py
I would like to import a function from file3 into file2. What is the easiest way to do it? I would also like to avoid manually appending to PYTHONPATH, to make this as smooth as possible for the next person pulling the project.
So far tried relative imports, which didn't work, possibly because I did not specify something in the init, which is currently empty. The error I am getting using:
from ..package.folder3.file3 import function_name
is
ImportError: attempted relative import with no known parent package
Thanks for all help!
The answer to your question is pretty simple, you need to add your package path to the system path.
Here is a complete example:
In file3.py, let's create a simple function
def func():
print("Hello from file3")
In file2.py, we can import func function like so:
import os
import sys
sys.path.append(os.path.abspath('../../..'))
# import func now from file3
from package.folder3.file3 import func
func() #should return "Hello from file3"
Hopefully, this answers your question!

Python not able to reference module in parent

I am trying to set up a library in python. I have created a setup.py file and in a folder under that I have a library folder, and then I tried to create an sample and test folder (for sample code and tests that I would include)
Folders:
- setup.py
- cvImageUtils # this is the library
- __init__.py # this includs ColorUtils
- ColorUtils.py # this includes a class called ColorUtils
- examples
- color.py # this is shown below
init.py in ColorUtils folder
from . import ColorUtils
ColorUtils.py
class ColorUtils:
def __...
Color.py
from cvImageUtils import ColorUtils
m1 = cv2.imread(os.path.join(image_folder, "bb.jpeg"), 1) # 1 = load color
cv2.imshow('grayscale', ColorUtils.convert_rbg_to_grayscale(m1))
At first, it said, unable to find the module, so I added to the top of the file the following based on another SO solution:
import sys
sys.path.append('../')
Now that seems broken to me already, but it did get me past the no module found, but now it says ColorUtils has no method convert_rbg_to_grayscale. So Then I had to change it to ColorUtils.ColorUtils.convert_rbg_to_grayscale
cv2.imshow('grayscale', ColorUtils.ColorUtils.convert_rbg_to_grayscale(m1))
How can I setup the folder so that it allows me to include the library without sys, and call it without declaring ColorUtils twice.
change your __init__.py:
from cvImageUtils.ColorUtils import ColorUtils
I don't think you'll need to import sys anymore, and you don't have import ColorUtils twice. but just like you have to instantiate an object, you should create a ColorUtils object.
my personal preference would be not creating a Class for Utils.
you might have done this already, but if you want to use a method straight from a class like you did in python, you might want to declare it static.
class ColorUtils:
#staticmethod
def util_method():
pass
then you can just do:
ColorUtils.util_method()
Update:
you can read more about relative/absolute import from here as well.
to fix your actual problem though, you can do:
color.py
remove your import sys and sys call from color.py
change: import cvImageUtils.ColorUtils as ct
to: from cvImageUtils.ColorUtils import *
remove all your ct reference instead just use the actual functions.
cvImageUtils/__init__.py
change: from . import ColorUtils
to __all__=['ColorUtils']
I was able to run color.py to get all the images printed out on screen.
a image.png was also generated locally as well.
Every directory that you want to expose in module search(we usually hide test.py) in python need a init.py file. That should be rule of thumb, by using sys module you can add the module to your "module search path".
After having init.py in your directories, you need to import packages/modules/funcitons you want to use:-
import cvImageUtils.ColorUtils.convert_rbg_to_grayscale
You can execute following code in python to see, what have included in your sys path(used by python to search for modules/packages)
import sys
sys.path
Look into below links for more detailed explations
https://www.programiz.com/python-programming/package
https://www.programiz.com/python-programming/modules#search

Importing classes defined in the same module

I am having trouble using my classes that I've defined in a module. I've looked at this stackoverlfow post, and the answer seems to be "you don't need imports." This is definitely not the behavior I'm experiencing. I'm using Python 3.3. Here is my directory structure:
root/
__init__.py
mlp/
__init__.py
mlp.py
layers/
__init__.py
hidden_layer.py
dropout_layer.py
My problem is this: the class defined in dropout_layer.py extends the class in hidden_layer.py, but when I try to import hidden_layer, I sometimes get an error depending on the directory I execute my code from. For instance, from layers.hidden_layer import HiddenLayer then I run my code if I execute it from root/mlp. This import does not work, however, if I execute my code from root. This is strange behavior to me. How can I get this working correctly?
My only non-empty __init__.py file is in root/mlp/layers/:
# root/mlp/layers/__init__.py
__all__ = ['hidden_layer', 'dropout_layer']
In Python 3 you can prepend a . for an import relative to the location of the current module:
from .hidden_layer import HiddenLayer

Dynamic Module Python

I have a program that creates a module called "cool" using file operations. I later say import cool and then uses the cool module that was created.
Here is my directory
project/
main.py
modules/
maker.py
cool/ #this folder and its contents was made by maker.py
__init__.py
coolm.py
If I want to make my program into the .exe format, this strategy will not work anymore. Does anyone know another technique?
Note: I cannot use exec to use the cool module..
Import your module when you need it like this:
coolmod = __import__('coolm')
coolm.someproperty
Alternatively you could try:
import importlib
coolmod = importlib.import_module('coolm', 'cool')
This allows you to specify the package name as a second argument.

Python: Unit Testing Module and Relative Imports

Currently have the following file hierarchy:
\package
__init__.py
run_everything.py
\subpackage
__init__.py
work.py
work1.py
work2.py
\test
__init__.py
test_work.py
test_work1.py
My first question is regarding relative imports. Suppose in \subpackage\work.py I have a function called custom_function(), and I would like to test that function in test_work.py. For some reason I can not figure out how to make this import from one module to another. Trying from .. subpackage.work1 import custom_function() does not seem to work, and yields the error Attempted relative import in non-package Is there any way to resolve this?
2)
I would like to run all test files from run_everything.py with one function, would adding a suite() function in each test_work*.py file, which adds each unit_testing class to suite.addTest(unittest.makeSuite(TestClass)), and finally importing them into the top-level run_everything.py be the most conventional way in Python2.7?
Here is a hack*
Insert the path's to "subpackage" and "test" to your python path in run_everything using:
import sys
sys.path.insert(0, '/path/to/package/subpackage')
sys.path.insert(0, '/path/to/package/test')
And then, you can import all your files using vanilla imports in run_everything:
import work, work1, work2
import test_work, test_work1
*This won't permanently affect your PYTHONPATH.

Categories

Resources