Skip to content

Conditional import of StringIO from StringIO or cStringIO doesn't work #1169

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
gvanrossum opened this issue Jan 27, 2016 · 4 comments
Closed
Labels

Comments

@gvanrossum
Copy link
Member

This code:

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

doesn't work: it complains error: Name 'StringIO' already defined on the second import. I think this is because in cStringIO, the function StringIO is an overloaded function (returning different types with and without argument) while in StringIO.py there is a class StringIO.

I'm not sure how to fix this.

@JukkaL JukkaL added the feature label Jan 28, 2016
@JukkaL
Copy link
Collaborator

JukkaL commented Jan 28, 2016

I've seen cases like this as well (in the Python standard library).

When we have a conditional definition where one of the alternatives is a function and the other alternative is a class, we should probably generate a callable type as the result that isn't a type object. If the signatures are different, as in this case, we should try to calculate the most general signature that is compatible with both definitions.

@ddfisher ddfisher added this to the 0.4.0 milestone Mar 1, 2016
@ddfisher
Copy link
Collaborator

ddfisher commented Mar 2, 2016

Duplicate of #1107.

@ddfisher ddfisher closed this as completed Mar 2, 2016
@ddfisher ddfisher removed this from the 0.4.0 milestone Mar 2, 2016
@den-run-ai
Copy link

related to this, how do i properly annotate this code so that mypy checks these types? Right now mypy does not even complain if I remove the Union, BinaryIO, Optional.

def writeln(msg: str, file: Optional[Union[str, BinaryIO]] = None) -> None:
    msg += '\n'
    print(msg)
    if file:
        if isinstance(file, (str, six.text_type)):
            with open(file, mode='a') as f:
                f.write(msg)
        elif isinstance(file, six.StringIO):
            file.write(msg)
        else:
            raise Exception('bad file string(IO) {} with type {}'.format(file, type(file)))
    return

@JukkaL
Copy link
Collaborator

JukkaL commented Nov 13, 2018

@denfromufa Your problem doesn't look directly related to this issue. You can ask on Gitter or create a new issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants