Page 1 of 1

[SOLVED] imports issue

Posted: Wed May 22, 2019 7:51 am
by LukeVideo
Hello again,
I'm trying to import a module to connect to my wifi. i'm using a module because i don't want the ssid or password to be tracked on github :mrgreen:

But it don't work in my main.py. In repl it works fine, I import ConnectWifi in both main.py and in the repl prompt and :

Code: Select all

connect to wifi
Traceback (most recent call last):
File "main.py", line 15, in <module>
NameError: name 'ConnectWiFi' isn't defined
MicroPython v1.10-331-ge38c68310-dirty on 2019-05-09; ESP32 module with ESP32
Type "help()" for more information.
>>> import ConnectWifi
>>> ConnectWifi.greetings()
Hellooooo !
>>>
You'll notice the first line is a print statement from these few lines of code :

Code: Select all

import ConnectWifi
try:
  ConnectWifi
except NameError:
  print("no ConnectWifi")
else:
  print("connect to wifi")
  ConnectWiFi.greetings()
  
I'm trying to check if the import failed or not, it seems to pass but then i can't call it. ConnectWifi.greetings fails and the whole file fails.

Am i doing something wrong?

Re: imports issue

Posted: Wed May 22, 2019 8:54 am
by LukeVideo
Oh... I was trying to import the file and not the functions within. So it works in repl but in a .py file you should import a class or a function not the file directly...
:oops:

Re: imports issue

Posted: Wed May 22, 2019 9:06 am
by jimmo
You should be able to do exactly what you did in the REPL from main.py

It's just like regular Python. If you have foo.py containing "def bar".

Code: Select all

import foo
foo.bar()
or

Code: Select all

from foo import bar
bar()

Re: imports issue

Posted: Wed May 22, 2019 9:16 am
by LukeVideo
well, i'm not sure why it didn't work. I'm not a python expert so i thought it might be because there a just functions in the file and no class ? So i should import the function from the file ?

Anyway this works fine

Code: Select all

from ConnectWifi import connect
connect()
Is the usual import refere to a class named like the file so that python knows what to do ? In my case in the ConnectWifi there is no ConnectWifi class...

Re: imports issue

Posted: Wed May 22, 2019 9:23 am
by jimmo
As far as imports go, there's no distinction between classes, functions or just plain old variables.

It just so happens that in the "import foo" case, the "foo" you get looks a bit like a class because you use the "." notation to access its contents.

i e. if this was foo.py

Code: Select all

def bar():
  print('bar')
  
class Thing:
  def baz():
    print('baz')
  
x = 22
then

Code: Select all

import foo

foo.bar()

t = foo.Thing()
t.baz()

print(foo.x)

Re: imports issue

Posted: Thu May 23, 2019 8:16 am
by LukeVideo
Thanks jimmo for the example.
i still don't really understand why my

Code: Select all

import foo

foo.bar()
returned foo isn't defined ???

Anyway it's all good now.

Thanks.