Cannot find reference python

Python – Cannot find reference ‘xxx’ in __init__.py

All of my __init__.py , except for the one right above Sources are blank files. I am receiving a lot of warnings of the kind:

Cannot find reference ‘xxx’ in __init__.py

For example, my FiltersController.py has this piece of code:

import numpy.random as npr bootstrap = npr.choice(image_base.data[max(0, x-2):x+3, max(0, y-2):y+3].flatten(), size=(3, 3), replace=True) 

Cannot find reference ‘choice’ in __init__.py

I’m googling wondering what does this mean and what should I do to code properly in Python.

Best Solution

This is a bug in pycharm. PyCharm seems to be expecting the referenced module to be included in an __all__ = [] statement.

For proper coding etiquette, should you include the __all__ statement from your modules? ..this is actually the question we hear young Spock answering while he was being tested, to which he responded: «It is morally praiseworthy but not morally obligatory.»

To get around it, you can simply disable that (extremely non-critical) (highly useful) inspection globally, or suppress it for the specific function or statement.

  • put the caret over the erroring text (‘choice’, from your example above)
  • Bring up the intention menu (alt-enter by default, mine is set to alt-backspace)
  • hit the right arrow to open the submenu, and select the relevant action

PyCharm has its share of small bugs like this, but in my opinion its benefits far outweigh its drawbacks. If you’d like to try another good IDE, there’s also Spyder/Spyderlib.

I know this is quite a bit after you asked your question, but I hope this helps (you, or someone else).

Edited: Originally, I thought that this was specific to checking __all__ , but it looks like it’s the more general ‘Unresolved References’ check, which can be very useful. It’s probably best to use statement-level disabling of the feature, either by using the menu as mentioned above, or by specifying # noinspection PyUnresolvedReferences on the line preceding the statement.

Python – What does ‘super’ do in Python? – difference between super().__init__() and explicit superclass __init__()

What’s the difference?

SomeBaseClass.__init__(self) 

means to call SomeBaseClass ‘s __init__ . while

means to call a bound __init__ from the parent class that follows SomeBaseClass ‘s child class (the one that defines this method) in the instance’s Method Resolution Order (MRO).

Читайте также:  Javascript get page height

If the instance is a subclass of this child class, there may be a different parent that comes next in the MRO.

Explained simply

When you write a class, you want other classes to be able to use it. super() makes it easier for other classes to use the class you’re writing.

As Bob Martin says, a good architecture allows you to postpone decision making as long as possible.

super() can enable that sort of architecture.

When another class subclasses the class you wrote, it could also be inheriting from other classes. And those classes could have an __init__ that comes after this __init__ based on the ordering of the classes for method resolution.

Without super you would likely hard-code the parent of the class you’re writing (like the example does). This would mean that you would not call the next __init__ in the MRO, and you would thus not get to reuse the code in it.

If you’re writing your own code for personal use, you may not care about this distinction. But if you want others to use your code, using super is one thing that allows greater flexibility for users of the code.

Python 2 versus 3

This works in Python 2 and 3:

This only works in Python 3:

It works with no arguments by moving up in the stack frame and getting the first argument to the method (usually self for an instance method or cls for a class method — but could be other names) and finding the class (e.g. Child ) in the free variables (it is looked up with the name __class__ as a free closure variable in the method).

I used to prefer to demonstrate the cross-compatible way of using super , but now that Python 2 is largely deprecated, I will demonstrate the Python 3 way of doing things, that is, calling super with no arguments.

Indirection with Forward Compatibility

What does it give you? For single inheritance, the examples from the question are practically identical from a static analysis point of view. However, using super gives you a layer of indirection with forward compatibility.

Forward compatibility is very important to seasoned developers. You want your code to keep working with minimal changes as you change it. When you look at your revision history, you want to see precisely what changed when.

Читайте также:  Object properties to array php

You may start off with single inheritance, but if you decide to add another base class, you only have to change the line with the bases — if the bases change in a class you inherit from (say a mixin is added) you’d change nothing in this class.

In Python 2, getting the arguments to super and the correct method arguments right can be a little confusing, so I suggest using the Python 3 only method of calling it.

If you know you’re using super correctly with single inheritance, that makes debugging less difficult going forward.

Dependency Injection

Other people can use your code and inject parents into the method resolution:

class SomeBaseClass(object): def __init__(self): print('SomeBaseClass.__init__(self) called') class UnsuperChild(SomeBaseClass): def __init__(self): print('UnsuperChild.__init__(self) called') SomeBaseClass.__init__(self) class SuperChild(SomeBaseClass): def __init__(self): print('SuperChild.__init__(self) called') super().__init__() 

Say you add another class to your object, and want to inject a class between Foo and Bar (for testing or some other reason):

class InjectMe(SomeBaseClass): def __init__(self): print('InjectMe.__init__(self) called') super().__init__() class UnsuperInjector(UnsuperChild, InjectMe): pass class SuperInjector(SuperChild, InjectMe): pass 

Using the un-super child fails to inject the dependency because the child you’re using has hard-coded the method to be called after its own:

>>> o = UnsuperInjector() UnsuperChild.__init__(self) called SomeBaseClass.__init__(self) called 

However, the class with the child that uses super can correctly inject the dependency:

>>> o2 = SuperInjector() SuperChild.__init__(self) called InjectMe.__init__(self) called SomeBaseClass.__init__(self) called 

Addressing a comment

Why in the world would this be useful?

Python linearizes a complicated inheritance tree via the C3 linearization algorithm to create a Method Resolution Order (MRO).

We want methods to be looked up in that order.

For a method defined in a parent to find the next one in that order without super , it would have to

  1. get the mro from the instance’s type
  2. look for the type that defines the method
  3. find the next type with the method
  4. bind that method and call it with the expected arguments

The UnsuperChild should not have access to InjectMe . Why isn’t the conclusion «Always avoid using super «? What am I missing here?

The UnsuperChild does not have access to InjectMe . It is the UnsuperInjector that has access to InjectMe — and yet cannot call that class’s method from the method it inherits from UnsuperChild .

Both Child classes intend to call a method by the same name that comes next in the MRO, which might be another class it was not aware of when it was created.

Читайте также:  Как изменить цвет изображения html

The one without super hard-codes its parent’s method — thus is has restricted the behavior of its method, and subclasses cannot inject functionality in the call chain.

The one with super has greater flexibility. The call chain for the methods can be intercepted and functionality injected.

You may not need that functionality, but subclassers of your code may.

Conclusion

Always use super to reference the parent class instead of hard-coding it.

What you intend is to reference the parent class that is next-in-line, not specifically the one you see the child inheriting from.

Not using super can put unnecessary constraints on users of your code.

Python – __init__.py for

Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The __init__.py file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.

But just click the link, it contains an example, more information, and an explanation of namespace packages, the kind of packages without __init__.py .

Related Question

Источник

PyCharm не понимает методы OpenCV

Попробовал установить более старые версии OpenCV,другие версии интерпретатора и PyCharm, но тщетно. Вот тестовый код, больше ничего нету:

import pytesseract import cv2 img = cv2.imread("4.png") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) cnf = r"--oem 1 --psm 4" pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" text = pytesseract.image_to_string(img, config=cnf) print(text) 

Ответы (3 шт):

введите сюда описание изображения

Мне помогла установка библиотек именно в сам python и по совету одного паренька, перекинул файл cv2.pyd из папки cv2 в папку site-package и проблема была частично решена, код запускается, но выделение методов и отсутствие подсказок осталось.

введите сюда описание изображения

Была такая же ошибка, мне помогло просто в терминале в PyCharme написать pip install opencv-python. При этом я уже ставил до этого opencv, но заработал именно так

  1. В правом нижнем углу PyCharm выбираем Interpreter Settings
  2. В списке виртуальных окружений выбираем своё
  3. Нажимаем Show path for the selected interpreter
  4. Указываем путь /lib/python3.10/site-packages/cv2
  5. Не забываем Apply
Interpreter Settings. -> Show All. -> Show path for the selected interpreter -> [Add] -> /lib/python3.10/site-packages/cv2 -> [OK] -> [Apply] 

Источник

Оцените статью