Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cant import ABC but ABCMeta is correctly imported?

Tags:

python

abc

I got an example code that uses the abc package for python. I installed abc in my laptop using pip. The route to the package folder is correctly set the in PATH.

The example code that I got does:

'from abc import ABC, abstractmethod'

If I try to run it, I got 'ImportError: cannot import name ABC'. However, if I tried to import only 'abstractmethod' the import works.

I'm also able to import ABCMeta, just not ABC.

'from abc import ABC' <- dont work

'from abc import ABCMeta, abstractmethod' <- it does

It seems to be within the same package, and I didn't get error messages when I installed the package via pip. So, why I can import 'ABCMeta' and 'abstractmethod' but not 'ABC'?

like image 873
Anon Avatar asked Dec 31 '22 21:12

Anon


2 Answers

I found exactly what I was looking for here:

http://www.programmersought.com/article/7351237937/

Basically, in python 2.7 (which is the version I have to use because boss reasons) you use ABCMeta instead and you set your class to inherit from ABCMeta like:

from abc import ABCMeta, abstractmethod                                         

class MyBase():                                                                 
    __metaclass__ = ABCMeta                                                     
    @abstractmethod                                                             
    def func(self):                                                             

This was very helpful to me and I hope is for others.

like image 158
Anon Avatar answered Jan 14 '23 13:01

Anon


abc.ABC had been introduced in Python 3.4.
So, you should use a version ≥ 3.4 to run the code.

bpo-16049: Add abc.ABC class to enable the use of inheritance to create ABCs, rather than the more cumbersome metaclass=ABCMeta. Patch by Bruno Dupuis.

like image 30
abc Avatar answered Jan 14 '23 15:01

abc