About import modules in python - python

import nibabel
nibabel.processing.resample_to_output(input_img, voxel_size)
AttributeError: module 'nibabel' has no attribute 'processing'
import nibabel
import nibabel.processing
nibabel.processing.resample_to_output(input_img, voxel_size)
Why does the first code fail but the second code work?

Expanding on #juanpa answer in the comments, you can simply consider these as two different modules.
For this
import nibabel
You get the error which suggests that this module does not have an attribute named processing
But for this
import nibabel.processing
It works fine since itself can be considered a module and thus means that processing is not an attribute of nibabel.
So it looks the code that you are trying to run only requires the 2nd import and not the first.

Related

AttributeError: module 'pandora' has no attribute 'util'

I have a github repo named pandora:
https://github.com/akshkr/pandora-python
In the test_case_refactor branch, I can't use submodules of pandora such as pn.util.misc.seed_everything() gives me the following error.
AttributeError: module 'pandora' has no attribute 'util'
I doubted circular imports so moved every import inside function wherever possible but didn't seem to work. And the test-cases written inside the module are passing.
Can someone tell me what exact issue is causing this AttributeError?
Since misc is a python script and not a module in itself, you need to either import the function itself
from pandora.util.misc import seed_everything
seed_everything()
OR, you can import the misc script from util module
from pandora.util import misc
misc.seed_everything()

Name re is not defined although re is imported in module and in main code

I'm working on a Jupyter Notebook for my master's thesis and I'd like to keep it clean. I use a lot of functions to assign categories to groups of data.
Therefore, I've decided to put all those functions in a functions.py module which I import at the start of my notebook. My notebook has the following imports:
import sys
sys.path.append('../src/') # ugly hack to be able to import the functions module
import re
import numpy as np
import pandas as pd
import seaborn as sns
import functions as fn
One of my functions uses the "re" module for matching strings with regex. When I called the said function I get NameError: ("name 're' is not defined", 'occurred at index 0') so I figured I had to import re at the beginning of my functions.py file. This didn't change anything. So I even tried to put import re in the function body, but it wouldn't work either.
I have absolutely no idea why re doesn't work despite trying to import it everywhere.
Note: my functions worked correctly when I was defining and using them from the notebook so I know for certain it's not a bug in my function.
Solved my own issue, the answer is stupidly simple: Jupyter doesn't take into account any edits to an imported module even if you reimport it. If you make any changes to a module you have to shut down the kernel and restart it, import again and the edits will work.
In my particular case I had added import re to my functions.py but Jupyter didn't take it into account until I restarted the kernel.
In a notebook, you can use the importlib library and call importlib.reload(module) instead of restarting the kernel

Unable to import modules using [dot]module

I'm trying to make use of some parts of the Source code for statsmodels.iolib.summary2. If I try to run the source code in its entirety I'm getting the error:
ModuleNotFoundError: No module named 'main.table'; 'main' is not a package
This is raised after:
from .table import SimpleTable
From the post What does a . in an import statement in Python mean? I'm able to understand why this error is raised conceptually (at best), but I have no Idea how to work around it.
What I've tried:
From the comments we have:
[...] It basically means the current namespace or package directory
This made me think that it was imported from textwrap, but it doesn't seem that way. Since statsmodels is often imported like import statsmodels.api as sm i thought that it would be a similar thing with Simpletable, so I've tried importing it in different ways and with different combinations of statsmodels and statsmodels.compat.collections since these are also used in the beginning of the source:
from statsmodels.compat.python import (lrange, iterkeys, iteritems, lzip,
reduce, itervalues, zip, string_types,
range)
from statsmodels.compat.collections import OrderedDict
import numpy as np
import pandas as pd
import datetime
import textwrap
from .table import SimpleTable
from .tableformatting import fmt_latex, fmt_txt
I've also tried to install SimpleTable (conda), but I think I'm just way off target here, so any suggestions would be great!
Try from statsmodels.iolib.table import SimpleTable instead if you've already installed statsmodel module via pip/conda. It's a class defined inside statsmodels.iolib.table package/file :)

What are the rules for importing with "as" in Python without using from

I was trying to import the following function in Python 2.7
import scipy.signal.savgol_filter as sgolay
I received the following error:
ImportError: No module named savgol_filter
savgol_filter is a function, not a module, so the error makes some sense. My question then is, is it not possible to import, without the use of the word "from" anything besides a module?
In other words, the following works:
from scipy.signal import savgol_filter as sgolay
But in general, does the following "sub_part" need to be a module?
import my_module.sub_part as some_name
I've seen lots of writing suggesting "sub_part" does not need to be a module. Is there something tricky going on with scipy that is making this not work?
Thanks,
Jim
In general, if you do import thing, import thing.subthing, import thing.subthing.subsubthing, etc., the far-right thing needs to be a module. Only the from form allows importing things that aren't modules. If you want a definitive statement of the forms of the import statement and what it allows, the Python language reference explains it in great detail, but it's a pretty dense read.
import is for importing modules. If you are not importing modules then you should see if its an object and create an instance like this:
import scipy as sp
sgolay = scipy.signal.savgol_filter
#Other stuff to do...

Python "import random" Error

As you may know from my previous posts, I'm learning Python. And this time I have a small error which I think is with this build of Python itself. When using the following:
import random
number = random.randint(1,10000)
Python gives me this error:
File "C\Users\name\Documents\Python\random.py", line 5, in (module)
print random.random()
TypeError: 'module' object is not callable
Every time I try to run it. Me no understand. Any help would be much appreciated!
EDIT: The two lines of code I'm trying to run:
import random
print random.randint(1,100)
That's it. And it gives me the same error.
By naming your script random.py, you've created a naming conflict with the random standard library module.
When you try to run your script, the directory containing the script will be added to the start of the module import path. So when your script does import random, you're effectively running a second copy of the script as the random module.
When the random module runs import random, it means that random.random will also be a reference to your module. So when you attempt to call the random.random() standard library function, you're actually attempting to call the module object resulting in the error you got.
If you rename your script to something else, the problem should go away.
Even I faced the same problem. I have renamed my python file from random.py to shuffle.py. This didn't work out. Then I changed the version then it worked. This may help a bit.
Python version : 3.6.7
replace
import random;
to
import random2;
I am using pycharm and I had to take the additional step to import the methods from random. In my case:
import random
from random import choice
The simple answer: Change your filename from "random.py" to something else as it is conflicting with random library.

Categories