TypeError: __init__() got an unexpected keyword argument 'type'
  • 11-Jun-2023
Lightrun Team
Author Lightrun Team
Share
TypeError: __init__() got an unexpected keyword argument 'type'

TypeError: __init__() got an unexpected keyword argument ‘type’

Lightrun Team
Lightrun Team
11-Jun-2023

Explanation of the problem

 

When attempting to import the compile_graphql_to_cypher function from the graphql_compiler module, a TypeError occurs. The traceback reveals that the error originates from the __init__() method in the schema.py file of the graphql_compiler package. More specifically, the error occurs at line 26, where a GraphQLArgument object is created with the type parameter set to GraphQLNonNull(GraphQLString). However, examining the GraphQLArgument constructor in graphql-core version 2.3.2, it appears that the expected parameter name is type_ instead of type. This inconsistency causes the unexpected keyword argument ‘type’ error.

Code Block:

 

FilterDirective = GraphQLDirective(
    name='filter',
    args=OrderedDict([(
        'op_name', GraphQLArgument(
            type=GraphQLNonNull(GraphQLString),
            description='Name of the filter operation to perform.',
        )),
        ('value', GraphQLArgument(
            type=GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString))),
            description='List of string operands for the operator.',
        ))]
    ),
)

 

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for: TypeError: __init__() got an unexpected keyword argument ‘type’

 

To resolve this issue, you can consider upgrading the graphql_compiler package to a version that is compatible with the graphql-core package you have installed. The error seems to suggest that the graphql_compiler package is using an outdated parameter name in the GraphQLArgument constructor, which has been corrected in later versions. You can try installing a newer version of the graphql_compiler package, such as version 2.0.0dev, which might have addressed this issue.

Code Block:

 

pip install graphql-compiler==2.0.0dev

 

Alternatively, if upgrading the graphql_compiler package is not feasible or does not resolve the issue, you can modify the affected code in the schema.py file yourself. Update the GraphQLArgument constructor to use the type_ parameter instead of type. Make this change in the local installation of the graphql_compiler package to ensure compatibility with your current version of graphql-core.

Code Block:

 

# In graphql_compiler/schema.py
class GraphQLArgument(object):
    __slots__ = "type", "default_value", "description", "out_name"

    def __init__(
        self,
        type_,  # type: Union[GraphQLInputObjectType, GraphQLNonNull, GraphQLList, GraphQLScalarType]
        default_value=None,  # type: Optional[Any]
        description=None,  # type: Optional[Any]
        out_name=None,  # type: Optional[str]
    ):
        # type: (...) -> None
        self.type = type_
        self.default_value = default_value
        self.description = description
        self.out_name = out_name

 

Please note that modifying the package code directly is not recommended unless you have a specific reason to do so and are aware of the potential implications. It is generally recommended to use official package releases or seek assistance from the package maintainers for resolution.

 

Other popular problems with graphql-compiler

 

Problem 1: One common problem encountered with graphql-compiler is the issue of incompatible package versions. When using graphql-compiler alongside other related packages such as graphql-core, it is crucial to ensure compatibility between their versions. Incompatibilities may result in errors or unexpected behavior during runtime. For example, attempting to import a specific function or class from graphql-compiler may throw a ModuleNotFoundError or other import-related errors.

To address this problem, it is recommended to carefully review the version requirements and compatibility guidelines provided by the graphql-compiler documentation or repository. Ensure that all required packages are installed and that their versions align with each other. Upgrading or downgrading the package versions may be necessary to establish a compatible environment.

Problem 2: Another common issue that users face with graphql-compiler is related to query compilation errors. During the process of compiling GraphQL queries to a specific target language or format, syntax or semantic errors in the queries can lead to compilation failures. These errors may manifest as exceptions, warnings, or incomplete/incorrect output.

To address query compilation errors, it is crucial to carefully review the GraphQL query syntax and semantics. Validate the queries using a GraphQL query validator or editor, such as GraphiQL or GraphQL Playground, to identify any syntax errors or inconsistencies. Additionally, consult the graphql-compiler documentation for specific guidelines and best practices when writing queries for compilation.

Problem 3: A third common problem encountered with graphql-compiler is performance issues during query compilation. Depending on the complexity and size of the GraphQL schema and queries, the compilation process may consume a significant amount of computational resources and time. This can lead to slow performance and delayed responses, especially in scenarios with large-scale GraphQL schemas or complex queries.

To improve the performance of query compilation with graphql-compiler, consider implementing optimization techniques and strategies. This may include implementing caching mechanisms to store previously compiled queries, optimizing the GraphQL schema design to reduce complexity, or utilizing specialized compilation options and flags provided by the graphql-compiler package. Monitoring system resources, such as CPU and memory usage, can also help identify performance bottlenecks and guide further optimizations.

Please note that the specific solutions to these problems may vary depending on the context and the exact nature of the encountered issues. It is recommended to consult the graphql-compiler documentation, issue tracker, or community forums for more detailed troubleshooting steps and guidance.

 

A brief introduction to graphql-compiler

graphql-compiler is a powerful tool used for compiling GraphQL queries into executable code or other target languages. It provides a framework for transforming GraphQL queries, schemas, and related metadata into optimized representations suitable for execution in various environments. The compiler takes advantage of the GraphQL introspection capabilities to analyze and process queries, ensuring efficient and accurate translation.

At its core, graphql-compiler offers a set of modules and utilities for parsing, validating, and transforming GraphQL queries and schemas. It leverages the capabilities of graphql-core and other related packages to handle the underlying GraphQL operations effectively. By using graphql-compiler, developers can optimize and customize the query compilation process according to their specific requirements, resulting in improved performance and maintainability of GraphQL applications.

Additionally, graphql-compiler provides a flexible architecture that allows for extension and integration with other tools and frameworks in the GraphQL ecosystem. It supports the modularization of compiler functionality, enabling developers to add custom plugins or transformations tailored to their application’s needs. This extensibility makes graphql-compiler a versatile tool that can adapt to different use cases and environments.

Overall, graphql-compiler empowers developers to efficiently compile and process GraphQL queries, enabling seamless integration of GraphQL into their applications while ensuring high performance and maintainability.

 

Most popular use cases for graphql-compiler

 

  1. Query Optimization: graphql-compiler can be used to optimize GraphQL queries by transforming them into more efficient representations. It analyzes the structure of the queries, identifies common patterns, and generates optimized code that minimizes unnecessary database or API calls. This optimization can significantly improve the performance of GraphQL applications, especially when dealing with complex or nested queries. Here’s an example of using graphql-compiler to optimize a GraphQL query:

 

from graphql_compiler import compile_graphql_to_cypher

# GraphQL query before optimization
query = """
    query {
        user(id: "123") {
            name
            posts {
                title
                comments {
                    content
                }
            }
        }
    }
"""

# Compile the query to optimized code
optimized_code = compile_graphql_to_cypher(query)

# Use the optimized code for execution
execute(optimized_code)

 

  1. Code Generation: graphql-compiler can generate code in different target languages based on GraphQL schemas and queries. This feature allows developers to automatically generate client-side or server-side code that interfaces with GraphQL APIs. By leveraging graphql-compiler‘s code generation capabilities, developers can save time and effort in manually writing code for GraphQL operations. Here’s an example of generating TypeScript code from a GraphQL schema using graphql-compiler:

 

# Generate TypeScript code from GraphQL schema
graphql-compiler --schema schema.graphql --output generated/typescript

# The generated TypeScript code can be used in the application
import { Query, Mutation } from './generated/typescript'

 

  1. Custom Transformations: graphql-compiler provides a framework for creating custom transformations on GraphQL queries and schemas. Developers can extend the compiler’s functionality by implementing their own transformations or plugins. This flexibility allows for advanced customization and integration with specific requirements or existing tools. Here’s an example of creating a custom transformation using graphql-compiler:

 

from graphql_compiler import CompilerContext, CompilerPlugin

class MyCustomTransformation(CompilerPlugin):
    def transform_query(self, context: CompilerContext):
        # Perform custom transformations on the query
        ...

# Create the compiler with the custom transformation
compiler = create_compiler(plugins=[MyCustomTransformation()])

# Compile and execute GraphQL queries using the customized compiler
optimized_code = compiler.compile(query)
execute(optimized_code)

 

These are just a few examples of the versatile use cases for graphql-compiler. It provides developers with powerful tools to optimize queries, generate code, and customize the compilation process, enabling efficient and flexible GraphQL development.

 

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.