我可以导入与标准库同名的本地模块吗?

时间:2019-08-05 20:23:11

标签: python python-import

我创建了自己的名为queue的模块,并试图将其导入。但是,当尝试使用它时,出现错误'Queue' object has no attribute 'enqueue'

如何导入自己的队列( 有一个enqueue),而不是标准库的队列(没有)?

def driver():
    import queue
    q = queue.Queue()
    for line in df:
        if 'received' in line:
            q.enqueue(line)
            print("Adding job " + new_item.job_ID + " to the queue with the timestamp: " + new_item.time_stamp + ".")
            print("The prority of the job is: " + new_item.job_priority)
            print("The job type is: " + new_item.job_type)

4 个答案:

答案 0 :(得分:1)

在Python 2.x中,您可以通过在任何其他导入之前添加以下行来消除本地queue与标准库之间的歧义:

from __future__ import absolute_import

...然后使用:

import .queue as local_queue
q = local_queue.Queue()

...获得自己的实现,而不是标准实现。


在Python 3中,此行为是默认行为,因此您不需要from __future__ import就能使用import .queue从同一包或目录中的queue.py显式导入作为您当前的代码。

答案 1 :(得分:0)

我认为问题在于python正在导入其内置模块队列,因此,当实例化Queue类时,您正在创建pthon内置类型队列的对象。

此问题的解决方案是更改模块和类名,并且在创建函数,与内置函数,模块或名同名的模块或类时,python中存在此约定。应该在自己的模块和类的末尾添加一个_

所以,可以尝试

 queue ==> queue_
 Queue ==> Queue_ 

答案 2 :(得分:0)

将内部文件重命名为my_queue.py之类的文件,然后将其导入到您的文件中。这样可以避免诸如from queue import *之类的不良做法,并且避免名称与标准库冲突,这很可能是您现在遇到的问题。

import my_queue

def driver():
    q = my_queue.Queue()
    for line in df:
        if 'received' in line:
            q.enqueue(line)
            print("Adding job " + new_item.job_ID + " to the queue with the timestamp: " + new_item.time_stamp + ".")
            print("The prority of the job is: " + new_item.job_priority)
            print("The job type is: " + new_item.job_type)

答案 3 :(得分:-1)

尝试一下:

from queue import *

q = Queue ()

def driver():
    for line in df:
        if 'received' in line:
            q.enqueue(line)
            print("Adding job " + new_item.job_ID + " to the queue with the timestamp: " + new_item.time_stamp + ".")
            print("The prority of the job is: " + new_item.job_priority)
            print("The job type is: " + new_item.job_type)