Google Colab custom module has no attribute
Asked Answered
T

3

6

What I am trying to do is to define a function in a custom module on Google Colab. I created a *.py file to define the function. It is

/content/gdrive/My Drive/Colab/myfunc.py

Then I created a *.ipynb file at the same folder. It is

/content/gdrive/My Drive/Colab/test.ipynb

In myfunc.py, the code is

def somefunc(a)
  return a*2

In test.ipynb, the code is

cd /content/gdrive/My\ Drive/Colab
import myfunc
myfunc.somefunc(2)

Then it occurs error "AttributeError: module 'myfunc' has no attribute 'somefunc'"

I also used

   dir(myfunc)

in test.ipynb, which shows

['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__']

My function 'somefunc' is not in the attributes!!!

This problem only occurs on Colab. I tried it on my computer and an online Jupyter notebooks. They are both working correctly.

PS: No matter whether I put an empty __init__.py file in the same folder or not, the problem always exists.

Tweedsmuir answered 16/3, 2019 at 4:51 Comment(0)
Q
0

You likely need to adjust your sys.path.

Here's a complete example showing how to create a module and import it into Colab: https://colab.research.google.com/drive/1PtYW0hZit-B9y4PL978kV2ppJJPhjQua

The key line in this example for you to add, I believe, is:

# Add the local_modules directory to the set of paths
# Python uses to look for imports.
import sys
sys.path.append('local_modules')

You would need to adjust the path from 'local_modules' to something like /content/gdrive/My\ Drive/Colab.

Quacksalver answered 16/3, 2019 at 19:20 Comment(0)
B
0

In case anyone else stumbles upon this, copy all you need on /content level:

!cp -r ../drive/MyDrive/Colab .

and use them from there.

Bijugate answered 14/11, 2020 at 16:15 Comment(0)
T
-1

I was importing some custom functions from one colab file to another & got the same error even when the module imports are correctly done. So I just restarted my colab file & the issue got resolved.

Teal answered 14/5, 2022 at 14:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.