Relative imports in Python 3

前端 未结 16 1074
误落风尘
误落风尘 2020-11-21 06:42

I want to import a function from another file in the same directory.

Sometimes it works for me with from .mymodule import myfunction but sometimes I get

16条回答
  •  执念已碎
    2020-11-21 07:27

    I ran into this issue. A hack workaround is importing via an if/else block like follows:

    #!/usr/bin/env python3
    #myothermodule
    
    if __name__ == '__main__':
        from mymodule import as_int
    else:
        from .mymodule import as_int
    
    
    # Exported function
    def add(a, b):
        return as_int(a) + as_int(b)
    
    # Test function for module  
    def _test():
        assert add('1', '1') == 2
    
    if __name__ == '__main__':
        _test()
    

提交回复
热议问题