Search code examples
pythonscapypython-packaging

Circular import error only when importing specific function


I am using scapy 2.4.5 and am trying to use the UDP class.

from scapy.all import UDP

runs with no issue, but I can not use the IDE to go to declaration. If I click on it shows no declaration found. However if I use

from scapy.layers.inet import UDP

I can then go to the declaration and see the class and associated code. but when I run it I get the following error.

ImportError: cannot import name 'AnsweringMachine' from partially initialized module 'scapy.ansmachine' (most likely due to a circular import) 

There are no other imports and this is VERY basic

from scapy.layers.inet import UDP


if __name__ == "__main__":
    
    new_udp_packet = UDP()
    print(new_udp_packet)

expected output

WARNING: No IPv4 address found on en5 !
WARNING: No IPv4 address found on ap1 !
WARNING: more No IPv4 address found on awdl0 !
WARNING: Calling str(pkt) on Python 3 makes no sense!
b'\x005\x005\x00\x08\x00\x00'

Solution

  • The easy fix:

    import scapy.all  # makes sure everything gets imported in the right order
    from scapy.layers.inet import UDP
    

    Of course you'll then have to make sure the scapy.all import remains first in the file.

    However, I'd recommend looking into an IDE that can resolve imports through the scapy.all file... :)

    Since scapy.layers.all (which is what scapy.all imports) dynamically chooses the layer modules to load via scapy.conf.load_layers, it can unfortunately not work with code completion that doesn't evaluate code.