0

Sometimes, I see examples like this, but I don't understand how do they work. Imported module uses function without any places in which this function is set to use. Please can someone explain me how to use them.

Example:

from some_package import *

def some_func():
    # do_something
    pass
    
imported_func()

And then imported_func somehow defines some_func and uses it. How is this implemented? When I tried to call some_func from module.py I received an error. Again: idea is to use function from imported file which was defined in importing file. I couldn't find answer in google.

I tried:

from f.module import *
obj = cls()

def some_func():
    for _ in range(100):
        print("smth")
        
obj.imported_func()

Code in main.py

class cls:
    @staticmethod
    def imported_func():
        some_func()
    

Code in module.py

I have main.py and folder f in one directory. In folder f I have module.py

  • 1
    It's hard to understand what you are asking. What error do you get? Which files? It looks like you have imported `imported_func` from `some_package` (e.g. from the file `some_package.py`, though it could be from `some_package/__init__.py`). "imported_func somehow defines some_func and uses it" that's not what the code shows. "I tried to call some_func from module.py I received an error" ... is the code above in `module.py`? – Anentropic Jun 13 '22 at 10:17
  • Thanks, I extended question – Matvey_coder3 Jun 13 '22 at 11:54
  • For `f` to behave as a package you need to have an empty file `f/__init__.py`. But what you are trying to do will have a "circular import" problem (https://stackoverflow.com/questions/1556387/circular-import-dependency-in-python) i.e. `f/module.py` needs to import `some_func` from `main.py` and `main.py` needs to import `cls` from `f/module.py` – Anentropic Jun 13 '22 at 15:50
  • `imported_func` is a staticmethod so you don't need to instantiate the cls here `obj = cls()`, you can just do `cls.imported_func()` – Anentropic Jun 13 '22 at 15:51
  • and `cls` is a bad name for a class - convention in Python is to use CapitalCase names... additionally if you were to make a method with `@classmethod` then the convention is for the first arg to the method to be named `cls` ...so that would be very confusing – Anentropic Jun 13 '22 at 15:53

1 Answers1

0

The way to do this is at first import __main__ then call __main__.some_func(), but remember, it's not a good practice because at least you are reserving name, what can become common reason for errors.