Home > OS >  AttributeError: module 'nats' has no attribute 'connect'
AttributeError: module 'nats' has no attribute 'connect'

Time:06-02

https://nats-io.github.io/nats.py/modules.html

Traceback (most recent call last):
  File "c:\Users\lb\nats.py", line 22, in <module>
    asyncio.run(main())
  File "D:\anaconda\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "D:\anaconda\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "c:\Users\lb\nats.py", line 6, in main
    nc = await nats.connect(servers=["nats://216.48.189.5:4222"])
AttributeError: module 'nats' has no attribute 'connect'

An Attribute error: I am not able to figure out what is the issue with 'connect'.

import asyncio
import nats

async def main():
    # Connect to NATS!
    nc = await nats.connect(servers=["nats://216.48.189.5:4222"])

    # Receive messages on 'foo'
    sub = await nc.subscribe("foo")

    # Publish a message to 'foo'
    await nc.publish("foo", b'Hello from Python!')

    # Process a message
    msg = await sub.next_msg()
    print("Received:", msg)

    # Close NATS connection
    await nc.close()

if __name__ == '__main__':
    asyncio.run(main())

Help me with this connect issue, please.

CodePudding user response:

I just ran your code and got no error. Try uninstalling and reinstalling nats:

pip install nats-py

CodePudding user response:

The solution is to rename your file to anything else.

When you type import nats python recursively tries to find a file or folder named nats. In this case the first file if will find is nats.py.

You never define a function named connect in your nats.py so that fails. You want to instead let the recursive import continue upto site_packages where the actual nats folder is that contains the connect function.

For example, if you name this file hello.py:

import hello

print(hello.hello)
print(hello)
print(hello.hello.hello)

You will see that all 3 print statements print the same thing, since hello will be the file itself.

Simply renaming your file anything else will prevent python from finding the module too soon and will keep searching till it find the correct module.

  • Related